Skip to content

7. Error Handling

Barak Haim edited this page Apr 29, 2021 · 2 revisions

Handling Exceptions

try:
    <do something>
except <Exception_Type>:
    <handle the "Exception_Type">
except <Exception_name> as <new_name>:
    <handle the "Exception_Type" referenced as new_name>
except:
    <handle any error>
else:
    <come here if and only if no exception was raised>
finally:
    <cleanup eventually>

Raise Exceptions

raise <exception_type>

A list of python exceptions python exceptions.

About Try and Except in Python. Examples from medium.

The Assertions

assert <condition>, <optional error message>

Raises an AssertionError when isn't met. More about the assertion statment.

User-defined Exceptions

# Create a new class inheriting from Exception
class <new_exception_name>(Exception):
    pass

Clone this wiki locally