# Python : Core : Exceptions - [library/exceptions](https://docs.python.org/3/library/exceptions.html) #### Usage ###### Raising ```python raise # re-raise existing exception raise ErrorClass # will instantiate an instance with no args raise ErrorClass( ... ) # the most common use case raise ErrorClass( ... ) from e # raise new exception while chaining current one as "cause" raise ErrorClass( ... ) from None # disable automatic chaining ``` ###### Handling ```python try: ... # raise ... except SomeError: ... except ( Error1, ... ): # a tuple of errors to match ... except SomeError as e: # bind exception to variable "e" ... else: # runs if no exception raised ... finally: # always runs ... ``` #### Exception API * `__cause__` — the explicitly-chained exception (when using `raise from`); always displayed * `__context__` ­— the implicitly-chained exception; only displayed if `__cause__` is `None` and `__suppress_context__` is `False` * `__notes__` — list of added notes * `__str__()` — produces `"<Type>: <message>"` * `__suppress_context__` — is set to `True` when using `raise from`; controls whether `__context__` is displayed * `args` — the tuple of args given to the exception constructor * `add_note( note )` — add string `note`, which will appear in the traceback #### Exception Chaining If while in an `except` clause a new exception is raised, the previous one will be chained to it. If the new exception is raised using the `raise from` statement ("explicit chaining"), the output will read: "The above exception was the direct cause of the following exception:" Otherwise ("implicit chaining"), the output will read: "During handling of the above exception, another exception occurred:" #### Output Examples ###### Basic ```python try: raise Exception( "an error occurred" ) except Exception as e: e.add_note( "first note" ) e.add_note( "second note" ) raise ``` ```bash ofer@minime:~/src$ python foo.py Traceback (most recent call last): File "/home/ofer/src/foo.py", line 2, in <module> raise Exception( "an error occurred" ) Exception: an error occurred first note second note ``` ###### Chaining ```python try: raise Exception( "an error occurred" ) except Exception as e: e.add_note( "a note" ) raise ValueError( "a second error occurred" ) ``` ```bash Traceback (most recent call last): File "/home/ofer/src/foo.py", line 2, in <module> raise Exception( "an error occurred" ) Exception: an error occurred a note During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ofer/src/foo.py", line 5, in <module> raise ValueError( "a second error occurred" ) ValueError: a second error occurred ``` ###### Chaining With `raise from` ```python try: raise Exception( "an error occurred" ) except Exception as e: e.add_note( "a note" ) raise ValueError( "a second error occurred" ) from e ``` ```bash Traceback (most recent call last): File "/home/ofer/src/foo.py", line 2, in <module> raise Exception( "an error occurred" ) Exception: an error occurred a note The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ofer/src/foo.py", line 5, in <module> raise ValueError( "a second error occurred" ) from e ValueError: a second error occurred ``` #### Built-in ```python BaseException # base class of all exceptions GeneratorExit KeyboardInterrupt # Ctrl+c SystemExit # raised by sys.exit() Exception # base class of all non-fatal exceptions ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError BufferError EnvironmentError EOFError ImportError # raised when the import statement fails ModuleNotFoundError IOError LookupError IndexError KeyError MemoryError NameError # raised when a local or global name isn't found (.name) UnboundLocalError OSError BlockingIOError ChildProcessError ConnectionError BrokenPipeError ConnectionBrokenError ConnectionRefusedError ConnectionResetError FileExistsError FileNotFoundError InterruptedError IsADirectoryError NotADirectoryError PermissionError ProcessLookupError TimeoutError ReferenceError RuntimeError NotImplementedError # use this in your abstract base classes RecursionError StopAsyncIteration # async equivalent of StopIteration StopIteration # used by iterators and generators SyntaxError # can result from: __main__, import, compile(), exec(), or eval() IndentationError TabError SystemError # .code -> arg passed to sys.exit() (defaults to None) TypeError ValueError UnicodeError UnicodeDecodeError UnicodeEncodeError UnicodeTranslateError Warning BytesWarning DeprecationWarning EncodingWarning FutureWarning ImportWarning PendingDeprecationWarning ResourceWarning RuntimeWarning SyntaxWarning UnicodeWarning UserWarning ``` #### Standard Library ```python argparse ArgumentError < Exception ArgumentTypeError < Exception bdb BdbQuit < Exception csv Error < Exception curses error < Exception decimal DecimalException < ArithmeticError ... getopt GetoptError < Exception gzip BadGzipFile < OSError json JSONDecodeError < ValueError sqlite3 # exceptions defined by DB-API v2.0 Error < Exception DatabaseError DataError IntegrityError InternalError NotSupportedError OperationalError ProgrammingError InterfaceError Warning < Exception ssl SSLError < OSError CertificateError < ValueError SSLCertVerificationError < ValueError SSLEOFError SSLSyscallError SSLWantReadError SSLWantWriteError SSLZeroReturnError subprocess SubprocessError < Exception CalledProcessError tarfile TarError < Exception CompressionError ExtractError FilterError AbsoluteLinkError AbsolutePathError LinkOutsideDestinationError OutsideDestinationError SpecialFileError HeaderError ReadError StreamError zipfile BadZipFile < Exception LargeZipFile < Exception ```