In this article, we will cover python try except and finally statement with the help of code examples.
When your program detects an error, Python raises a number of exceptions (something in the program goes wrong). When certain exceptions occur, the Python interpreter terminates the current process and sends the control to the caller process until the exception is handled. If this is not done, the program will crash.
Consider the following program: function A calls function B, which calls function C. If an exception occurs in function C but is not handled there, it is sent to B and subsequently to A.
If this condition is not met, an error message is shown and our application comes to a quick and unexpected end.
Exceptions in Python are managed with a try statement.
- The try clause contains the critical operation that might cause an exception.
- The except clause contains the code that handles exceptions. Once we’ve caught the exception, we may pick which procedures to do. Here’s an example.
# import module sys to get the type of exception import sys randomList = ['x', 0, 4] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print(sys.exc_info(), "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
The entry is x <class 'ValueError'> occurred. Next entry. The entry is 0 <class 'ZeroDivisionError'> occured. Next entry. The entry is 4 The reciprocal of 4 is 0.25
In this program, we loop through the randomList list’s values. As previously stated, the section that might create an exception is contained within the try block. If no exceptions occur, the except block is skipped and normal flow resumes (for the last value). However, if an exception occurs, it is handled by the except block (first and second values).
Using the exc_info() function from the sys module, we output the name of the exception. We can see that results in a ValueError and 0 in a ZeroDivisionError.
Since every exception in Python inherits from the base Exception class, we can also perform the above task in the following way:
# import module sys to get the type of exception import sys randomList = ['x', 0, 4] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except Exception as e: print(e.__class__, "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
This program has the same output as the above program.
In the above example, no specific exception was mentioned in the except clause. This is a bad programming technique since it will catch all exceptions and treat each instance in the same manner. We may tell an except clause which exceptions to catch.
A try clause can contain an unlimited number of except clauses to handle various exceptions, but only one will be performed if an exception occurs.
In an except clause, we may declare several exceptions by using a tuple of values. Here’s some pseudo-code to get you started.
try: # do something pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass