2. 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.
3. Exception
• Example for syntax error
• Example for exception
• Division by zero
• Accessing a non existing element in the list
6. 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
7. Multiple except clause
• We an also use multiple except block to handle different
exception
• Please note that at most one handler will be executed.
8. 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
9. 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
14. 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