Python Language Exceptions
Internal
Overview
Exceptions are Python's main error handling mechanism. try/except
is a language-level mechanism to handle errors that may be caused by a section of the code. Exceptions can be triggered explicitly from the program code with raise
. A convenient way to conditionally trigger an exception (AssertionError
) in the code, use assert
.
try/except
try/except
is a language-level mechanism to handle errors (traceback) that may be caused by a section of the code. This syntax eliminates tracebacks.
try:
# do something
except:
# execute if the previous block caused an error
The code provided under except
is referred to as "exception handler". If an exception occurs in a try
block and it is not caught in the corresponding except
block, it bubbles up until is caught by a matching handler, in the calling layers. If no exception handler is found, Python prints and error message and some information about where the error occurred and then terminates the program.
If more than one type of exception could occur, it is best to provide a separate exception handler for each:
try:
# do something
except SomeError as ex:
# exception handler for 'SomeError'
except SomeOtherError as ex:
# exception handler for 'SomeOtherError'
finally:
# optional block to execute whether there are or not exceptions
finally
The finally
block is optional. If specified, is executed regardless of whether there was an exception or not, and after the exception was handled, if there was an exceptions.
raise
Avoid raising generic Exception
s, try to be specific as possible with the exception type and use the most specific exception type that semantically fits the issue.
raise ValueError('function invoked with no arguments')
assert
The assert
statement can be used to trigger an AssertionError
conditionally. It can be use with an optional error message, which is becoming part of the exception if the assertion proves false:
assert s is not None
assert s is not None, 'The string was supposed to be set!'
Exception Chaining
Exceptions can be chained, which preserves tracebacks:
raise RuntimeError('specific message') from error
Predefined Exceptions
BaseException ├─ SystemExit ├─ KeyboardInterrupt ├─ GeneratorExit └─ Exception ├─ StopIteration ├─ StopAsyncIteration ├─ ArithmeticError │ ├─ FloatingPointError │ ├─ OverflowError │ └─ ZeroDivisionError ├─ AssertionError ├─ AttributeError ├─ BufferError ├─ EOFError ├─ ImportError │ └─ ModuleNotFoundError ├─ LookupError │ ├─ IndexError │ └─ KeyError ├─ MemoryError ├─ NameError │ └─ UnboundLocalError ├─ OSError │ ├─ BlockingIOError │ ├─ ChildProcessError │ ├─ ConnectionError │ │ ├─ BrokenPipeError │ │ ├─ ConnectionAbortedError │ │ ├─ ConnectionRefusedError │ │ └─ ConnectionResetError │ ├─ FileExistsError │ ├─ FileNotFoundError │ ├─ InterruptedError │ ├─ IsADirectoryError │ ├─ NotADirectoryError │ ├─ PermissionError │ ├─ ProcessLookupError │ ├─ TimeoutError ├─ ReferenceError ├─ RuntimeError │ ├─ NotImplementedError │ └─ RecursionError ├─ SyntaxError │ └─ IndentationError │ └─ TabError ├─ SystemError ├─ TypeError ├─ ValueError │ └─ UnicodeError │ ├─ UnicodeDecodeError │ ├─ UnicodeEncodeError │ └─ UnicodeTranslateError └─ Warning ├─ DeprecationWarning ├─ PendingDeprecationWarning ├─ RuntimeWarning ├─ SyntaxWarning ├─ UserWarning ├─ FutureWarning ├─ ImportWarning ├─ UnicodeWarning ├─ BytesWarning ├─ EncodingWarning └─ ResourceWarning