Exceptions Handling#
Exceptions#
👉 When a Python script encounters a situation (an error) that it cannot cope with, it raises an exception.
👉 An exception is a Python object that represents an error.
👉 Python has many built-in exceptions that are raised when your program encounters an error.
👉 Exceptions must either handle the exception immediately otherwise it terminates and quits.
👉 When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
For example, let us consider a program where we have a function A that calls function B, which in turn calls function C. If an exception occurs in function C but is not handled in C, the exception passes to B and then to A.
If never handled, an error message is displayed and our program comes to a sudden unexpected halt.
Exception handling#
👉 In Python, exceptions can be handled using a try statement.
👉 The critical operation which can raise an exception is placed inside the try clause.
👉 The code that handles the exceptions is written in the except clause.
# Example 1:
try:
print(10 + '5')
except:
print('Something went wrong')
Something went wrong
# Example 2:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
Since every exception in Python inherits from the base Exception class, we can also perform the above task in the following way:
# Example 3:
# This program has the same output as the above program.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except Exception as e:
print("Oops!", e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In the following example, it will handle the error and will also tell us the kind of error raised.
# Example 5:
try:
name = input('Enter your name: ')
year_born = input('Year you were born: ')
age = 2022 - year_born
print(f'You are {name}. And your age is {age}.')
except TypeError:
print('Type error occured')
except ValueError:
print('Value error occured')
except ZeroDivisionError:
print('zero division error occured')
Enter your name: Milaan
Year you were born: 1926
Type error occured
Catching specific exceptions#
👉 In the above example, we did not mention any specific exception in the except clause.
👉 This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which exceptions an except clause should catch.
👉 A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
>>> 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
Raise exceptions#
👉 We can also manually raise exceptions using the raise keyword.
👉 We can optionally pass values to the exception to clarify why that exception was raised.
raise KeyboardInterrupt
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-6-c761920b81b0> in <module>
----> 1 raise KeyboardInterrupt
KeyboardInterrupt:
raise MemoryError("This is an argument")
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-7-51782e52f201> in <module>
----> 1 raise MemoryError("This is an argument")
MemoryError: This is an argument
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
Enter a positive integer: 9
except Clause with no exceptions#
You can also use the except statement with no exceptions defined as follows
>>> try:
>>> You do your operations here
>>> ......................
>>> except:
>>> If there is any exception, then execute this block.
>>> ......................
>>> else:
>>> If there is no exception then execute this block
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice.
except clause with multiple exceptions#
👉 You can also use the same except statement to handle multiple exceptions as follows −
>>>try:
>>> You do your operations here
>>> ......................
>>>except(Exception1[, Exception2[,...ExceptionN]]]):
>>> If there is any exception from the given exception list,
>>> then execute this block.
>>> ......................
>>>else:
>>> If there is no exception then execute this block.
try-finally clause#
👉 The try statement in Python can have an optional finally clause.
👉 This clause is always executed no matter what, and is generally used to release external resources.
You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −
>>> try:
>>> You do your operations here;
>>> ......................
>>> Due to any exception, this may be skipped.
>>> finally:
>>> This would always be executed.
>>> ......................
Note: You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause.
try:
fh = open("testfile.txt", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
# If you do not have permission to open the file in writing mode,
# then this will produce the following result −
Error: can't find file or read data