Python Language Exceptions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 34: Line 34:
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>
assert s is not None, 'The string was supposed to be set!'
assert s is not None, 'The string was supposed to be set!'
</syntaxhighlight>
=Exception Chaining=
Exceptions can be chained, which preserves tracebacks:
<syntaxhighlight lang='py'>
raise RuntimeError('specific message') from error
</syntaxhighlight>
</syntaxhighlight>
=Predefined Exceptions=
=Predefined Exceptions=

Revision as of 21:35, 16 February 2022

Internal

Overview

try/except is a language-level mechanism to handle errors (traceback) that may be caused by a section of the code.

To trigger an exception manually in the code use raise.

To conditionally trigger an exception 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

finally

raise

Avoid raising generic Exceptions, 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

https://docs.python.org/3/library/exceptions.html

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