Exception Handling
Code sample link: https://replit.com/@jjoco/python-exceptions
Let's say you wanted to execute some block of code, that could potentially throw an error (specifically called Exceptions). Normally, if a block of code throws an error, the currently executing program would crash. To prevent this from happening, one can wrap such block of code using try-except
blocks, which are try-catch
blocks in many other languages.
Basic try-except
The syntax for try-except
is the following:
1 2 3 4 |
|
try
block throws an Exception, then the program will execute an except
block to handle the Exception.
If the dev wants to do something with the Exception caught, then they can use the following syntax:
1 2 3 4 |
|
If it's possible that the try block can throw different types of Exceptions, then the try-except
can have multiple except
blocks, which execute when a specific Exception type is thrown:
Try-except with muiltiple excepts
1 2 3 4 5 6 |
|
The dev can also handle different Exceptions in the same except
block like the following:
Try-except with multiple exception types on one line
1 2 3 4 5 6 7 8 |
|
Finally
Finally, there's the finally
block, which generally executes right before the try
statement completes:
1 2 3 4 5 6 7 8 |
|
So if a try-finally
block looks like this:
1 2 3 4 |
|
Finally clause here
followed by the Exception
.
There are other complexities involving this finally
block, but that's out of the scope of this tutorial.