Guide on Python Exception handling.
What are exceptions?
An exception refers to an event that is triggered during the execution of a program that goes against the flow, disrupting the program.
An exception in Python is meant to represent a error that occurs due to Python being unable to handle an unexpected situation.
Python attempts to determine what is causing the error, and will return an exception that represents the type of error that has been caused. See full list of errors here.
Why do we use Exception handling?
When an error is thrown in python, the program will throw an exception and then shut it self down. This may not matter on a small script, but when we’re talking about proper applications, regardless of their scale, Python exceptions play a vital role.
As the name suggests, we can “handle” the exception. Instead of the program crashing, we can be prepared, and take the appropriate steps.
The act of handling of these errors in python, is known as python exception handling.
try: # Statement to be tested except: # Statement(s) to be executed if error occurs
As the name suggests, the “try” statement will try to execute the statements in it’s code block. If an error is produced, instead of the program crashing, the program flow will continue on to the except statement, executing the commands in it’s code block.
There is an optional statement we can include here,
finally. Similar to the
for loop’s else statement it executes once the
try and except blocks have finished executing. This statement will run regardless of whether an error is encountered or not.
Here’s an example demonstrating use of all statements.
x = 5 try: x = x / 0 except ZeroDivisionError: x = 0 print("Error detected, x set to 0") finally: print("loop over")
Keep in mind though, that’s its possible for an error to be thrown in the code block of the
except statement. Similarly, it’s possible to create nested try and except statements.
Another example of a zero division error and the output you can expect to receive.
x = x / 0
# Error Output Traceback (most recent call last): File "C:\Users\#####\Desktop\test.py", line 6, in <module> x = x / 0 ZeroDivisionError: division by zero
Handling multiple Exceptions
There can be more than just one except statement present, similar to the many number of
elif‘s that can be present in an
x = 5 try: x = x / 0 except ZeroDivisonError: print("ZeroDivisionError detected") except TypeError: print("TypeError detected") except: print("Unknown Error detected")
try..except statements are run and an error is thrown, only one except path will be followed. If a ZeroDivisonError occurs, the statements in that block will execute and the loop will end. If neither a ZeroDivisonError or TypeError occur, the final except statement will run by default.
Catching any Exception
A bit of a bonus tip. The following code will trigger for any exception that may occur.
try: # Code except: # Code
There may come a time where you want to trigger exceptions of your own. We can do so with the
raise statement. There are two ways of using the
raise statement to raise exceptions.
The first is a type neutral exception, that falls under no category.
x = input("Input a positive number") if int(x) < 0: raise Exception("Non Positive number entered")
# Output Traceback (most recent call last): File "C:\Users\#####\Desktop\test.py", line 12, in <module> raise Exception("Non Positive number entered") Exception: Non Positive number entered
You can also choose to raise specific exceptions like the Type-error exception, input-error exception, divide-by-zero exception and more.
x = 5 if type(x) != str: raise TypeError("Wrong data type")
# Output Traceback (most recent call last): File "C:\Users\#####\Desktop\test.py", line 13, in <module> raise TypeError("Wrong data type") TypeError: Wrong data type
if you ever end up needing to find out whether or not your try statement run without an error being thrown, you can make use of the
else statement. The
else statement, unlike the
finally statement, will only run if an error is not encountered.
x = 5 try: x = x / 0 except ZeroDivisonError: print("ZeroDivisionError detected") else: print("No Zero Division Errors detected")
This marks the end of the Python Exception Handling guide. Any suggestions or contributions for CodersLegacy are more than welcome. Furthermore, you may ask any relevant questions can be asked below in the comments section.