91
raise ValueError('A very specific bad thing happened.')
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_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_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')
try: some_code_that_may_raise_our_value_error() except ValueError as err: print(err.args)
('message', 'foo', 'bar', 'baz')
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!
type, value, traceback = sys.exc_info()
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]
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
>>> 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 error ValueError: oops! <modification>
raise error.with_traceback(sys.exc_info()[2])
raise RuntimeError('specific message') from error
raise ValueError, 'message' # Don't do this, it's deprecated!
raise 'message' # really really wrong. don't do this.
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.')
80
raise Exception("I know python!")
73
1. raise exception 2. raise exception (args) 3. raise 4. raise exception (args) from original_exception
#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
def somefunction(): print("some cleaning") a=10 b=0 result=None try: 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
class MyCustomException(Exception): pass a=10 b=0 reuslt=None try: 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 zero MyException Zero Division division by zero
64
if 0 < distance <= RADIUS: #Do something. elif RADIUS < distance: #Do something. else: raise AssertionError("Unexpected value of 'distance'!", distance)
50
raise SystemExit
raise SystemExit("program exited")