python


Exception Handling Syntax

Following is the syntax of a Python try-except-else block.


try: 
    You do your operations here; 
    ...................... 
except ExceptionI: 
    If there is ExceptionI, then execute this block. 
except ExceptionII: 
    If there is ExceptionII, then execute this block. 
    ...................... 
else: 
    If there is no exception then execute this block.
Remember !
In place of Exception I and Exception II , we have to use the names of Exception classes in Python Example:

a=int(input("Enter first no:"))
b=int(input("Enter second no:"))
try:
    c=a/b
    print("Div is",c)
except ZeroDivisionError:
    print("Denominator should not be 0")
d=a+b
print("Sum is",d) 

Output:

Enter first no:10
Enter second no:0
Denominator should not be 0
Sum is 10
Output:

Enter first no:10
Enter second no:3
Div is 3.3333333333333335
Sum is 13

Important Exception classes

Exception Class Description
Exception Base class for all exceptions
ArithmeticError​ Raised when numeric calculations fails​
FloatingPointError​ Raised when a floating point calculation fails​
ZeroDivisionError​ Raised when division or modulo by zero takes place for all numeric types​
OverflowError​ Raised when result of an arithmetic operation is too large to be represented​
ImportError​ Raised when the imported module is not found in Python version < 3.6​
ModuleNotFoundError​ Raised when the imported module is not found from Python version >=3.6​
LookUpError​ Raised when searching /lookup fails​
KeyError​ Raised when the specified key is not found in the dictionary​
IndexError​ Raised when index of a sequence is out of range​
NameError​ Raised when an identifier is not found in the local or global namespace​
UnboundLocalError​ Raise when we use a local variable in a function before declaring it.​
TypeError​ Raised when a function or operation is applied to an object of incorrect type​
ValueError​ Raised when a function gets argument of correct type but improper value​
AttributeError​ Raised when a non-existent attribute is referenced.​
OSError​ Raised when system operation causes system related error.​
FileNotFoundError​ Raised when a file is not present​
FileExistsError​ Raised when we try to create a directory which is already present​
PermissionError​ Raised when trying to run an operation without the adequate access rights.​
SyntaxError​ Raised when there is an error in Python syntax.​
IndentationError​ Raised when indentation is not specified properly.​

Handling multiple exceptions

A try statement may have more than one except clause for different exceptions. ​br But at most one except clause will be executed​
Also , we must remember that if we are handling parent and child exception classes in except clause then the parent exception must appear after child exception , otherwise child except will never get a chance to run​.
Example:


import math​

    try:​
        x=10/5​

        print(x)​

        ans=math.exp(3)​

        print(ans)​
    except ZeroDivisionError:​

        print("Division by 0 exception occurred!")  ​

    except ArithmeticError:​

        print("Numeric calculation failed!")​
Output:

2.0
20.085536923187668


Single except multiple exception

If we want to write a single except clause to handle multiple exceptions , we can do this .​
For this we have to write names of all the exceptions within parenthesis separated with comma after the keyword except​ ​


while(True):​

    try:​

        a=int(input("Input first no:"))​

        b=int(input("Input second no:"))​

        c=a/b​

        print("Div is ",c)​

        break​

    except (ValueError,ZeroDivisionError):​

        print("Either input is incorrect or denominator is 0. Try again!")  ​
Output:

Input first no:4
Input second no:0
Either input is incorrect or denominator is 0. Try again!
Input first no:10
Input second no:bhopal
Either input is incorrect or denominator is 0. Try again!
Input first no:10
Input second no:4
Div is 2.5

Handling all exceptions

We can write the keyword except without any exception class name also .​
In this case for every exception this except clause will run .​
The only problem will be that we will never know the type of exception that has occurred!​


Exception Handling Syntax:

Following is the syntax of a Python handle all exception  block.


try: 
    You do your operations here; 
    ...................... 
except : 
    For every kind of exception this block will execute
Example

while(True):
    try:
        a=int(input("Input first no:"))
        b=int(input("Input second no:"))
        c=a/b
        print("Div is ",c)
        break
     except:
        print("Some problem occurred. Try again!")  
Output:

Input first no: 10
Input second no: 0
Some problem occurred. Try again!
Input first no: 10
Input second no: a
Some problem occurred. Try again!
Input first no: 10
Input second no: 4
Div is  2.5


Using Exception Object

Now we know how to handle exception, in this section we will learn how to access exception object in exception handler code.
To access the exception object created by Python we can use the keyword as and assign it to a variable.
Finally using that variable we can get the details of the exception
Example:


while(True):
    try:
        a=int(input("Input first no:"))
        b=int(input("Input second no:"))
        c=a/b
        print("Div is ",c)
        break;
    except (ValueError,ZeroDivisionError) as e:
        print(e)    

Output:

Input first no: 10
Input second no: 0
division by zero
Input first no: 10
Input second no: a
invalid literal for int() with base 10: 'a'
Input first no: 10
Input second no: 5
Div is  2.0


Obtaining Exception Details Using Traceback Class

Sometimes , we need to print the details of the exception exactly like Python does .
We do this normally , when we are debugging our code.
The module traceback helps us do this
This module contains a function called format_exc( )
It returns complete details of the exception as a string.
This string contains:
The program name in which exception occurred
Line number where exception occurred
The code which generated the exception
The name of the exception class
The message related to the exception
Example


import traceback
while(True):
    try:
        a=int(input("Input first no:"))
        b=int(input("Input second no:"))
        c=a/b
        print("Div is ",c)
        break
     except:
        print(traceback.format_exc())

Output:

Input first no:10
Input second no:0
Traceback (most recent call last):
  File "except5.py", line 6, in <module>
    c=a/b
ZeroDivisionError: division by zero
Input first no:10
Input second no:bhopal
Traceback (most recent call last):
  File "except5.py", line 5, in <module>
    b=int(input("Input second no:"))
ValueError: invalid literal for int() with bas 10: 'bhopal'


Raising an exception

We can force Python to generate an Exception using the keyword raise.
This is normally done in those situations where we want Python to throw an exception in a particular condition of our choice
Syntax:


raise ExceptionClassName
raise ExceptionClassName( message )


The finally block

If we have a code which we want to run in all situations, then we should write it inside the finally block.
Python will always run the instructions coded in the finally block.
It is the most common way of doing clean up tasks , like, closing a file or disconnecting with the DB or logging out the user etc


Syntax of finally block

The finally block has 2 syntaxes: Syntax 1

try:
    # some exception generating code
except :
    # exception handling code
finally:
    # code to be always executed
Syntax 2

try:
    # some exception generating code
finally:
    # code to be always executed

Example:

while(True):
    try:
        a=int(input("Input first no:"))
        b=int(input("Input second no:"))
        c=a/b
        print("Div is ",c)
        break;
    except ZeroDivisionError:
        print("Denominator should not be zero") 
    finally:
        print("Thank you for using the app!")   

Output:

Input first no: 10
Input second no: 0
Denominator should not be zero
Thank you for using the app!
Input first no: 10
Input second no: 5
Div is  2.0
Thank you for using the app!
Input first no: 10
Input second no: a
Thank you for using the app!
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "except8.py", line 4, in <module>
    b=int(input("Input second no:"))
ValueError: invalid literal for int() with base 10: 'a'