Exceptions are errors in our program that causes Python to stop and display an error message. Exceptions are handled using the try-except-finally block.
We want to avoid catastrophic errors.
Exception Handling
As mentioned before, we handle exceptions using the try-except-finally block. The try block is where you put the code that could potentially throw an exception. The except block is where you can gracefully perform an action if an exception was indeed thrown. Lastly, the finally block allows you to run code no matter if an exception was thrown or not.
You can use the else block to run code when no exceptions were thrown. This is similar to the finally block except that the finally block runs no matter what whereas the else block runs only when the code was exception-free.
When the situation arises, you might want to raise an exception yourself. This is done using the raise keyword:
PYTHON
raise Exception("Sorry, this is an exception!")
BASH
Traceback (most recent call last):
File "C:\Users\Sabe\sabe.py", line 1, in <module>
raise Exception("Sorry, this is an exception!")
Exception: Sorry, this is an exception!
This is useful especially if you're writing your own module because it allows users of your module to then handle your exceptions themselves and handle it however they want.