Often times we have errors in our programs. When we get an error, our program crashes. This may happen sometimes unexpectedly, and there is no way around it. In these cases, we must use a few methods to catch these errors and prevent our program from dying.

Try: try a snippet of code. It it doesn’t work move to exceptions

except: catches the error resulted from the code from the try segment. Runs another piece of code reactionary.

Finally: executes some code regardless of the previous error/non-error state.

https://www.youtube.com/watch?v=brICUKrzVR0&t=5s

he will tell us some exceptions.

In his code, he will have the following error when attempting to divide by 0:

he gets the ZeroDivisionError. This is an error that we can catch.

Depending on the type of error, we can get a different exception code.

our try and except will look like this:

if an exception occurs in the try block, then the code executor immediately jumps to the except block where the code continues executing.

Difference between except and catch

Catch will only catch specific exception codes, except will catch all exceptions.

Below is an example of a catch:

it will only except if the error above is the ZeroDivisionError exception.

You can have multiple catches as well:

https://stackoverflow.com/questions/11551996/why-do-we-need-the-finally-clause-in-python

the finally block is optional, its very useful for cleanup like closing files because it gets run regardless of program behavior. It is literally one of the very few lines of code that always runs.

no matter if there is a unforeseen catch, or secondary error, finally will always run.