02 Nov Exception Handling in Python
What is exception?
An exception is an error that occurs while a program is running, causing the program to abruptly halt.
Below are some common exceptions in Python:
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
For example:
#this program check voting eligibility def main(): #get the age age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") main()
Output: Enter your age thirty Traceback (most recent call last): File "F:/../exception.py", line 19, inmain() File "F:/../exception.py", line 10, in main age=int(input("Enter your age")) ValueError: invalid literal for int() with base 10: 'thirty'
So what all information we get from this message:
- The lengthy error message that is shown in the sample run is called a traceback.
- The traceback gives information regarding the line number(s) that caused the exception.
- The last line shows the name of the exception (ZeroDivisionError) and a brief description of the error that caused the exception to be raised (integer division or modulo by zero).
How to write Exception Handler?
try: #this program check voting eligibility def main(): #get the age try: age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") except: print("age must be a valid number") main()
try-except clause with multiple except clause.
#this program check voting eligibility def main(): #single try statement can have multiple except statements. try: age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") except ValueError: print("age must be a valid number") except IOError: print("Enter correct value") #generic except clause, which handles any exception. except: print("An Error occured") main()
How does it work?
If exceptions will occur in the code written in try blocks then the execution will stopped in try block and control will jump down to the except block.
How to display an Exception’s Default Error Message
def main(): try: age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") #display exception's default error message except ValueError as err: print(err) except: print("An Error occured") print("rest of the code...") main()
Output: Enter your age thirty invalid literal for int() with base 10: ' thirty' rest of the code...
The else clause
else block executed after the statements in the try block, only if no exceptions were raised. If an exception is raised, the else block is skipped.
#this program check voting eligibility def main(): try: age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") #display exception's default error message except ValueError as err: print(err) else: # code to be excuted when there is no exception print("Thank you, you have successfully checked the voting eligibility") main()
Output: Enter your age 24 Eligible to vote Thank you, you have successfully checked the voting eligibility
Output: Enter your age thirty invalid literal for int() with base 10: ' thirty'
The finally clause
The statements in the finally block are always executed whether an exception occurs or not.
The purpose of the finally block is to perform clean-up operations, such as closing files or other resources.
#this program check voting eligibility def main(): try: age=int(input("Enter your age")) if age>18: print("Eligible to vote") else: print("Not eligible to vote") #display exception's default error message except ValueError as err: print(err) finally: # code to be excuted whether exception occurs or not #typically for closing files and other resources print("Thank you") main()
#in case of no exception Output: Enter your age 34 Eligible to vote Thank you
#in case of exception Output: Enter your age fifty invalid literal for int() with base 10: ' fifty' Thank you
Raising an Exception
we can raise exception whenever our program attempts to do something erroneous or meaningless.
#this program check voting eligibility def main(): age=int(input("Enter your age ")) if age>18: print("Eligible to vote") else: # raising exception if age is not valid # The code below to this would not be executed # if we raise the exception raise ValueError("Invalid age") print("rest of the code...") main()
Output: Enter your age 13 Traceback (most recent call last): File "F:/REBOOT/exception.py", line 17, in main raise ValueError("Invalid age") ValueError: Invalid age
No Comments