Exceptions
Contents
1.4.4. Exceptions#
Even if a program syntax is correct, there might be issues that occur at runtime. To prevent the program from crashing Python provides a way to handle exceptions.
1.4.4.1. Handling Exceptions#
The basic form of exception handling is as follow:
try:
pass
except SomeException:
pass
...
except Exception as e:
pass
In this example we try
to execute something. In case it goes wrong, an exception while be raised.
The except
statement let us capture the exception for us to handle. We can optionally use the as
statement, giving access of the exception instance within the except
section.
Each except
statement will be will try to match the exception type in order.
The Exception
class acts as a wild card to catch (almost) everything.
try:
1/0
except ZeroDivisionError:
print("[ERROR] Impossible to divide by 0.")
except Exception as e:
pass
[ERROR] Impossible to divide by 0.
1.4.4.2. Raising Exceptions#
The raise
statement force an exception to occur.
try:
raise TypeError("Wrong type")
except OSError:
print("OSError occurred")
except TypeError:
print("TypeError occurred")
except Exception:
print("Exception occurred")
TypeError occurred
1.4.4.3. Clean-Up Actions#
After handling an exception, we might need to have some clean-up action. For example, to release some resources.
The finally
statement can be used after the except
statements and is always executed, regardless of an error occurring or not.
try:
raise Exception
except:
print("Handling Exception")
finally:
print("Clean-up action")
Handling Exception
Clean-up action