raise ValueError('A very specific bad thing happened.')
不要引发泛型异常
避免引发泛型Exception。要捕获它,您必须捕获所有其他更具体的子类异常。
问题1:隐藏错误
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',)
问题2:抓不到
更具体的捕获不会捕获一般异常:
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
>>> catch_error_modify_message()Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 3, in catch_error_modify_messageFile "<stdin>", line 2, in errorValueError: oops! <modification>
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'''
和用法:
if important_key not in resource_dict and not ok_to_be_missing:raise MyAppLookupError('resource is missing, and that is not ok.')
def somefunction():print("some cleaning")
a=10b=0result=None
try:result=a/bprint(result)
except Exception: # Output ->somefunction() # Some cleaningraise # Traceback (most recent call last):# File "python", line 8, in <module># ZeroDivisionError: division by zero
4.从original_exception引发例外(args)
此语句用于创建异常链,其中响应另一个异常引发的异常可以包含原始异常的详细信息-如下面的示例所示。
class MyCustomException(Exception):pass
a=10b=0reuslt=Nonetry:try:result=a/b
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 Divisiondivision by zero
class MyModuleBaseClass(Exception):pass
class MoreSpecificException(MyModuleBaseClass):pass
# To raise custom exceptions, you can just# use the raise keywordraise MoreSpecificExceptionraise MoreSpecificException('message')