To use exception handling in python, we first need to catch the all except clauses.
Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed.
try: some_statements_here except: exception_handling
Let’s see above syntax with a very simple example −
try: print("Hello, World!") except: print("This is an error message!")
Above is a very simple example, let’s understand the above concept with another example −
import sys List = ['abc', 0, 2, 4] for item in List: try: print("The List Item is", item) r = 1/int(item) break except: print("Oops!",sys.exc_info(),"occured.") print('\n') print("Next Item from the List is: ") print() print("The reciprocal of",item,"is",r)
The List Item is abc Oops! <class 'ValueError'> occured. Next Item from the List is: The List Item is 0 Oops! <class 'ZeroDivisionError'> occured. Next Item from the List is: The List Item is 2 The reciprocal of 2 is 0.5
In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block.
In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors −
Raised in case we cannot open the file.
Raised in case module is missing.
It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function.
Whenever the user hits the interrupt key (generally control-c)
Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.