Python Tutorials-Exceptions

An exception occurs when your code has something that is illogical to Python and causes an exception or error to occur. As with any programming language it becomes necessary to handle exceptions when your program starts to deal with a large number of external variables (and in some cases internal code).

First let’s talk about the difference between an exception and an error. An exception is a small issue that you would like to handle within the code, for example a print output indicating that a file wasn’t found.

An error on the other hand you do not want to happen. An error in your code usually does not get handled by the code, and usually means bad things will happen…really bad. Alright, not that bad but still, we don’t want errors.

So let’s take a look at exception handling…

Since a was set to a string by placing quotation marks around it Python cannot add 1 to it. However a better way to handle this would be:

This is set up almost identically as the previous example except that we have Python run a different function if the first function does not work, rather than just printing something out.

Give these a try, get familiar with exception handling.