如何在python中引发异常,以便稍后可以通过 except 块
except
yqkkidmi1#
抛出异常的另一种方法是 assert . 您可以使用assert来验证条件是否满足,如果不满足,则它将引发 AssertionError . 有关更多详细信息,请查看此处。
assert
AssertionError
def avg(marks): assert len(marks) != 0,"List is empty." return sum(marks)/len(marks)mark2 = [55,88,78,90,79]print("Average of mark2:",avg(mark2))mark1 = []print("Average of mark1:",avg(mark1))
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
qvsjd97n2#
为此,您应该学习python的raise语句。它应该放在试块内。范例-
try: raise TypeError #remove TypeError by any other error if you wantexcept TypeError: print('TypeError raised')
try:
raise TypeError #remove TypeError by any other error if you want
except TypeError:
print('TypeError raised')
inb24sb23#
您可能还希望引发自定义异常。例如,如果您正在编写一个库,那么为您的模块创建一个基本异常类,然后定制更具体的子异常,这是一个非常好的实践。你可以这样做:
class MyModuleBaseClass(Exception): passclass MoreSpecificException(MyModuleBaseClass): pass# To raise custom exceptions, you can just# use the raise keywordraise MoreSpecificExceptionraise MoreSpecificException('message')
class MyModuleBaseClass(Exception):
pass
class MoreSpecificException(MyModuleBaseClass):
# To raise custom exceptions, you can just
# use the raise keyword
raise MoreSpecificException
raise MoreSpecificException('message')
如果您对自定义基类不感兴趣,可以从普通异常类继承自定义异常类,如 Exception , TypeError , ValueError 等
Exception
TypeError
ValueError
9ceoxa924#
使用语义上适合您的问题的最具体的异常构造函数。在信息中要具体,例如:
raise ValueError('A very specific bad thing happened.')
避免提出一般性建议 Exception . 要捕获它,您必须捕获它的子类的所有其他更具体的异常。
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
例如:
def demo_bad_catch(): try: raise ValueError('Represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('Caught this error: ' + repr(error))>>> demo_bad_catch()Caught this error: ValueError('Represents a hidden bug, do not catch this',)
def demo_bad_catch():
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)
更具体的捕获不会捕获一般异常:
def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch exception: Exception')>>> demo_no_catch()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in demo_no_catchException: general exceptions not caught by specific handling
def demo_no_catch():
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
相反,使用语义上适合您的问题的最具体的异常构造函数。
raise ValueError('A very specific bad thing happened')
它还方便地允许将任意数量的参数传递给构造函数:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
这些参数由 args 属性在 Exception 对象例如:
args
try: some_code_that_may_raise_our_value_error()except ValueError as err: print(err.args)
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
印刷品
('message', 'foo', 'bar', 'baz')
在Python2.5中,实际的 message 属性已添加到 BaseException 有利于鼓励用户将异常子类化并停止使用 args ,但引入 message 原来对args的不赞成已经被撤回。
message
BaseException
例如,在except子句中,您可能希望记录发生了特定类型的错误,然后重新引发。在保留堆栈跟踪的同时执行此操作的最佳方法是使用裸raise语句。例如:
logger = logging.getLogger(__name__)try: do_something_in_app_that_breaks_easily()except AppError as error: logger.error(error) raise # just this! # raise AppError # Don't do this, you'll lose the stack trace!
logger = logging.getLogger(__name__)
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
您可以使用保留stacktrace(和错误值) sys.exc_info() ,但这更容易出错,并且在Python2和Python3之间存在兼容性问题,更倾向于使用裸机 raise 重提。解释 sys.exc_info() 返回类型、值和回溯。
sys.exc_info()
raise
type, value, traceback = sys.exc_info()
这是python 2中的语法-注意,这与python 3不兼容:
raise AppError, error, sys.exc_info()[2] # avoid this.# Equivalently, as error *is* the second object:raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
如果您愿意,您可以修改新加薪的情况,例如设置新加薪 args 例如:
def error(): raise ValueError('oops!')def catch_error_modify_message(): try: error() except ValueError: error_type, error_instance, traceback = sys.exc_info() error_instance.args = (error_instance.args[0] + ' <modification>',) raise error_type, error_instance, traceback
def error():
raise ValueError('oops!')
def catch_error_modify_message():
error()
except ValueError:
error_type, error_instance, traceback = sys.exc_info()
error_instance.args = (error_instance.args[0] + ' <modification>',)
raise error_type, error_instance, traceback
我们在修改args时保留了整个回溯。请注意,这不是最佳实践,而且在Python3中是无效语法(这使得保持兼容性更加困难)。
>>> catch_error_modify_message()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in catch_error_modify_message File "<stdin>", line 2, in errorValueError: oops! <modification>
>>> catch_error_modify_message()
File "<stdin>", line 3, in catch_error_modify_message
File "<stdin>", line 2, in error
ValueError: oops! <modification>
在python 3中:
raise error.with_traceback(sys.exc_info()[2])
再次强调:避免手动操作回溯。它的效率更低,更容易出错。如果您使用线程和 sys.exc_info 您甚至可能会得到错误的回溯(特别是当您对控制流使用异常处理时——我个人倾向于避免这种情况)
sys.exc_info
在python 3中,可以链接异常,以保留回溯:
raise RuntimeError('specific message') from error
注意:这允许更改引发的错误类型,并且这与python 2不兼容。
这些可以很容易地隐藏甚至进入生产代码。您希望引发异常,执行这些操作将引发异常,但不是预期的异常!以下内容在python 2中有效,但在python 3中无效:
raise ValueError, 'message' # Don't do this, it's deprecated!
仅在更旧版本的python(2.4及更低版本)中有效,您可能仍然会看到人们提出字符串:
raise 'message' # really really wrong. don't do this.
在所有的现代版本中,这实际上会引起 TypeError ,因为你不是在抚养孩子 BaseException 类型。如果您没有检查正确的异常,并且没有一个了解该问题的审阅者,那么它可能会投入生产。
我提出异常,以警告用户如果不正确使用我的api:
def api_func(foo): '''foo should be either 'baz' or 'bar'. returns something very useful.''' if foo not in _ALLOWED_ARGS: raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
我想故意犯一个错误,这样它就会进入异常状态您可以创建自己的错误类型,如果您想指出应用程序中的某些特定错误,只需在异常层次结构中对适当的点进行子类化:
class MyAppLookupError(LookupError): '''raise this when there's a lookup error for my app'''
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
使用方法:
if important_key not in resource_dict and not ok_to_be_missing: raise MyAppLookupError('resource is missing, and that is not ok.')
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
50pmv0ei5#
不要这样做。举杯 Exception 绝对不是正确的做法;请看aaron hall的精彩答案。再也没有比这更像Python的了:
raise Exception("I know python!")
如果需要更多信息,请参阅python的raise语句文档。
siv3szwd6#
在python3中,rasing异常有4种不同的语法:
1. raise exception 2. raise exception (args) 3. raise4. raise exception (args) from original_exception
1. raise exception
2. raise exception (args)
3. raise
4. raise exception (args) from original_exception
1.引发异常与2.引发异常(args)如果你使用 raise exception (args) 若要引发异常,则 args 将在打印异常对象时打印,如下面的示例所示。
raise exception (args)
# raise exception (args) try: raise ValueError("I have raised an Exception") except ValueError as exp: print ("Error", exp) # Output -> Error I have raised an Exception #raise execption try: raise ValueError except ValueError as exp: print ("Error", exp) # Output -> Error
# raise exception (args)
raise ValueError("I have raised an Exception")
except ValueError as exp:
print ("Error", exp) # Output -> Error I have raised an Exception
#raise execption
raise ValueError
print ("Error", exp) # Output -> Error
3.提高 raise 不带任何参数的语句重新引发最后一个异常。如果捕获异常后需要执行某些操作,然后希望重新引发异常,则此选项非常有用。但是如果以前没有例外的话, raise 声明提出 TypeError 例外。
def somefunction(): print("some cleaning")a=10b=0 result=Nonetry: result=a/b print(result)except Exception: #Output -> somefunction() #some cleaning raise #Traceback (most recent call last): #File "python", line 8, in <module> #ZeroDivisionError: division by zero
def somefunction():
print("some cleaning")
a=10
b=0
result=None
result=a/b
print(result)
except Exception: #Output ->
somefunction() #some cleaning
raise #Traceback (most recent call last):
#File "python", line 8, in <module>
#ZeroDivisionError: division by zero
4.从原始异常引发异常(args)此语句用于创建异常链接,其中为响应另一个异常而引发的异常可以包含原始异常的详细信息,如下例所示。
class MyCustomException(Exception):passa=10b=0 reuslt=Nonetry: try: result=a/b except ZeroDivisionError as exp: print("ZeroDivisionError -- ",exp) raise MyCustomException("Zero Division ") from expexcept MyCustomException as exp: print("MyException",exp) print(exp.__cause__)
class MyCustomException(Exception):
reuslt=None
except ZeroDivisionError as exp:
print("ZeroDivisionError -- ",exp)
raise MyCustomException("Zero Division ") from exp
except MyCustomException as exp:
print("MyException",exp)
print(exp.__cause__)
输出:
ZeroDivisionError -- division by zeroMyException Zero Division division by zero
ZeroDivisionError -- division by zero
MyException Zero Division
division by zero
0md85ypi7#
对于常见的情况,您需要抛出异常以响应某些意外情况,并且您永远不打算捕获异常,而只是快速失败以使您能够在发生异常时进行调试,最符合逻辑的情况似乎是 AssertionError :
if 0 < distance <= RADIUS: #Do something.elif RADIUS < distance: #Do something.else: raise AssertionError("Unexpected value of 'distance'!", distance)
if 0 < distance <= RADIUS:
#Do something.
elif RADIUS < distance:
else:
raise AssertionError("Unexpected value of 'distance'!", distance)
myss37ts8#
首先阅读现有答案,这只是一个附录。请注意,您可以提出带参数或不带参数的异常。例子:
raise SystemExit
退出程序,但您可能想知道发生了什么。因此,您可以使用此选项。
raise SystemExit("program exited")
这将在关闭程序之前向stderr打印“程序已退出”。
yebdmbv49#
请注意:有时您确实希望处理泛型异常。如果您正在处理一组文件并记录错误,您可能希望捕获某个文件发生的任何错误,将其记录下来,然后继续处理其余的文件。在这种情况下,一个
try: foo() except Exception as e: print(e) # Print out handled error
foo()
except Exception as e:
print(e) # Print out handled error
积木是一种很好的方法。你还是会想要的 raise 具体的例外情况,所以你知道它们的意思。
9条答案
按热度按时间yqkkidmi1#
抛出异常的另一种方法是
assert
. 您可以使用assert来验证条件是否满足,如果不满足,则它将引发AssertionError
. 有关更多详细信息,请查看此处。qvsjd97n2#
为此,您应该学习python的raise语句。它应该放在试块内。范例-
inb24sb23#
您可能还希望引发自定义异常。例如,如果您正在编写一个库,那么为您的模块创建一个基本异常类,然后定制更具体的子异常,这是一个非常好的实践。
你可以这样做:
如果您对自定义基类不感兴趣,可以从普通异常类继承自定义异常类,如
Exception
,TypeError
,ValueError
等9ceoxa924#
如何在python中手动引发/引发异常?
使用语义上适合您的问题的最具体的异常构造函数。
在信息中要具体,例如:
不要提出一般性异常
避免提出一般性建议
Exception
. 要捕获它,您必须捕获它的子类的所有其他更具体的异常。问题1:隐藏bug
例如:
问题2:我抓不住
更具体的捕获不会捕获一般异常:
最佳做法:提出声明
相反,使用语义上适合您的问题的最具体的异常构造函数。
它还方便地允许将任意数量的参数传递给构造函数:
这些参数由
args
属性在Exception
对象例如:印刷品
在Python2.5中,实际的
message
属性已添加到BaseException
有利于鼓励用户将异常子类化并停止使用args
,但引入message
原来对args的不赞成已经被撤回。最佳做法:例外条款
例如,在except子句中,您可能希望记录发生了特定类型的错误,然后重新引发。在保留堆栈跟踪的同时执行此操作的最佳方法是使用裸raise语句。例如:
不要修改你的错误。。。但如果你坚持的话。
您可以使用保留stacktrace(和错误值)
sys.exc_info()
,但这更容易出错,并且在Python2和Python3之间存在兼容性问题,更倾向于使用裸机raise
重提。解释
sys.exc_info()
返回类型、值和回溯。这是python 2中的语法-注意,这与python 3不兼容:
如果您愿意,您可以修改新加薪的情况,例如设置新加薪
args
例如:我们在修改args时保留了整个回溯。请注意,这不是最佳实践,而且在Python3中是无效语法(这使得保持兼容性更加困难)。
在python 3中:
再次强调:避免手动操作回溯。它的效率更低,更容易出错。如果您使用线程和
sys.exc_info
您甚至可能会得到错误的回溯(特别是当您对控制流使用异常处理时——我个人倾向于避免这种情况)Python3,异常链接
在python 3中,可以链接异常,以保留回溯:
注意:
这允许更改引发的错误类型,并且
这与python 2不兼容。
不推荐的方法:
这些可以很容易地隐藏甚至进入生产代码。您希望引发异常,执行这些操作将引发异常,但不是预期的异常!
以下内容在python 2中有效,但在python 3中无效:
仅在更旧版本的python(2.4及更低版本)中有效,您可能仍然会看到人们提出字符串:
在所有的现代版本中,这实际上会引起
TypeError
,因为你不是在抚养孩子BaseException
类型。如果您没有检查正确的异常,并且没有一个了解该问题的审阅者,那么它可能会投入生产。示例用法
我提出异常,以警告用户如果不正确使用我的api:
适当时创建自己的错误类型
我想故意犯一个错误,这样它就会进入异常状态
您可以创建自己的错误类型,如果您想指出应用程序中的某些特定错误,只需在异常层次结构中对适当的点进行子类化:
使用方法:
50pmv0ei5#
不要这样做。举杯
Exception
绝对不是正确的做法;请看aaron hall的精彩答案。再也没有比这更像Python的了:
如果需要更多信息,请参阅python的raise语句文档。
siv3szwd6#
在python3中,rasing异常有4种不同的语法:
1.引发异常与2.引发异常(args)
如果你使用
raise exception (args)
若要引发异常,则args
将在打印异常对象时打印,如下面的示例所示。3.提高
raise
不带任何参数的语句重新引发最后一个异常。如果捕获异常后需要执行某些操作,然后希望重新引发异常,则此选项非常有用。但是如果以前没有例外的话,raise
声明提出TypeError
例外。4.从原始异常引发异常(args)
此语句用于创建异常链接,其中为响应另一个异常而引发的异常可以包含原始异常的详细信息,如下例所示。
输出:
0md85ypi7#
对于常见的情况,您需要抛出异常以响应某些意外情况,并且您永远不打算捕获异常,而只是快速失败以使您能够在发生异常时进行调试,最符合逻辑的情况似乎是
AssertionError
:myss37ts8#
首先阅读现有答案,这只是一个附录。
请注意,您可以提出带参数或不带参数的异常。
例子:
退出程序,但您可能想知道发生了什么。因此,您可以使用此选项。
这将在关闭程序之前向stderr打印“程序已退出”。
yebdmbv49#
请注意:有时您确实希望处理泛型异常。如果您正在处理一组文件并记录错误,您可能希望捕获某个文件发生的任何错误,将其记录下来,然后继续处理其余的文件。在这种情况下,一个
积木是一种很好的方法。你还是会想要的
raise
具体的例外情况,所以你知道它们的意思。