Python Language Exceptions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 24: Line 24:


=<tt> assert </tt>=
=<tt> assert </tt>=
The <code>assert</code> statement can be used to trigger exceptions conditionally. It can be use with an optional error message, which is becoming part of the exception if the assertion proves false:
The <code>assert</code> statement can be used to trigger an <code>AssertException</code> conditionally. It can be use with an optional error message, which is becoming part of the exception if the assertion proves false:
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>
assert s is not None
assert s is not None

Revision as of 06:11, 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

raise must be followed by an exception, not a string.

assert

The assert statement can be used to trigger an AssertException 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!'