Exception Handling
In Python programming, there are many built-in exceptions which forces the program to output an error when something in it goes wrong. These type of runtime errors may occur during the program execution because of the presence of some illegal code. Examples of built-in exceptions are ZeroDivisionError, TypeError, IOError, ValueError, ImportError etc.
When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, the program will stop abnormally. As a result, the remaining code will be skipped. The following example shows this:
# except01.py
def divide(x, y):
# integer division
result = x // y
print("Result :", result)
# Look at the parameters and follow functioning of program
divide(10, 0) # illegal operation
divide(25, 4) # skipped
Output:
except01.py", line 3, in divide
result = x // y
ZeroDivisionError: integer division or modulo by zero
The try-except clauses
In the above code, the exception named “ZeroDivisionError” can be handled using “try-except” clauses. A code statement which can raise an exception is placed inside the try clause and the code that handles exception is written in the except clause.
Now, after adding “try-except” clauses the remaining code will be executed normally. See the modified code below:
# except02.py
def divide(x, y):
try:
# integer division
result = x // y
print("Result :", result)
except ZeroDivisionError:
print("Division by zero!")
# Look at the parameters and follow functioning of program
divide(10, 0) # illegal operation
divide(25, 4) # executes normally
Output:
Division by zero!
Result : 6
Multiple exceptions
Python can also handle multiple exceptions in the same code. That means, we can define as many exception blocks as we want, e.g. if we want to execute a special block of code for a specific kind of error. See the code below:
# except03.py
def divide(x, y):
try:
# Floor Division : integer division
result = x // y
print("Result :", result)
except ZeroDivisionError:
print("Division by zero!")
except TypeError:
print("Type Error!")
# Look at the parameters and follow functioning of program
divide(10, 0) # illegal operation
divide(25, 4)
divide(50, 'A') # illegal operation
divide(100, 10)
Output:
Division by zero!
Result : 6
Type Error!
Result : 10
The else clause
There is another clause named else which defines a block of code to be executed if no exception is raised. Here, we have used generic exception in the except clause (i.e. no specific exception being used).
The following example shows what happens if no exception is raised:
# except04.py
try:
print("Inside try!");
except:
print("Inside except!");
else:
print("Inside else!")
Output:
Inside try!
Inside else!
The finally clause
The finally clause lets us execute code regardless of whether exception has occurred or not. See the following code:
# except05.py
def divide(x, y):
try:
# integer division
result = x // y
print("Result :", result)
except:
print("Division by zero!")
finally:
print("Inside finally!!")
# Look at the parameters and follow functioning of program
divide(100, 10)
Output:
Result : 10
Inside finally!!
User-defined exception
The following example demonstrates how to create and use an user-defined (i.e. customized) exception in Python. In this example, if the temperature is greater than 35 degrees centigrade, a user-defined exception named TempTooHotException (which is a child class of Exception) will be raised. See the code below:
# except06.py
class TempTooHotException(Exception):
def __init__(self, value): #1
self.value = value
def __str__(self): #2
return repr(self.value)
try:
temp = float(input("Enter temperature value in centigrade: "))
if(temp>35.0):
raise TempTooHotException(temp) #1
else:
print("It's OK.")
except TempTooHotException as error:
print("An exception occurred:", error.value) #2
The program is run twice. See the output below.
Output:
Enter temperature value in centigrade: 41
An exception occurred: 41.0
Enter temperature value in centigrade: 36
It's OK.