EXCEPTION HANDLING IN
PYTHON
Dr. V.Sireesha
Dept. of CSE
Exception
• When runtime error occurs in program, it creates an exception
• When exception occurs ,
• Python interpreter will stop the current process
• Pass the exception to the calling process until it is handled
• If not handled , an error message is displayed and program comes to a
sudden unexpected halt
• Error in Python can be of two types
• Syntax errors –due to wrong syntax
• Exceptions- program is syntactically correct but the code resulted in an
error.
Exception
• Example for syntax error
• Example for exception
• Division by zero
• Accessing a non existing element in the list
Exception
• Accessing a key which is not present in dictionary
• Opening a non existing file
Exception Handling
Exception handling-using try and except
• Using try and except statement
• The critical operations which can raise an exception will be placed in try
clause
• The code that handles the exception will be placed in except block
Multiple except clause
• We an also use multiple except block to handle different
exception
• Please note that at most one handler will be executed.
Else clause
• In Python we can use an else clause on the try –except block
• The else clause must be present after all the except clause
• The code enters the else block only if the try clause does not
raise any exception
Finally keyword in Python
• Python provides a keyword finally, which is always executed
after try and except blocks.
• Generally used to release external resources.
• We must clean up the resource before the program comes to a
halt whether it successfully ran or not.
• These actions (closing a file, GUI or disconnecting from
network) are performed in the finally clause
Finally keyword in Python
Exception Handling
Raise an exception-raise
• We can also manually raise exceptions using the raise
keyword.
Raise an exception-raise
except Exception as e:
• if you want to print the message like what is an error in a
program then we use “e” which is the representation or object
of an exception.
• try:
print(5/0)
except Exception as e:
print("Error",e)
Output:
Error division by zero
Raising Exceptions
re-raise an exception
Instantiating an exception
Raise an exception with arguments
Handling Exceptions in invoked functions
Handling Exceptions in invoked functions
Handling Exceptions in invoked functions
Nested try
re-raise the exception
Assert
Assert

Exception Handling.pptx