Python Tutorial @ Home

Python Exception Handling

Python Exception
Common Exceptions
The problem without handling exceptions
Exception handling in python
The except statement with no exception
The except statement using with exception variable
Declaring Multiple Exceptions
The try…finally block
Raising exceptions

Python Exception Handling

Exception handling in python

The try-expect statement

If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. The try block must be followed with the except statement, which contains a block of code that will be executed if there is some exception in the try block.

Syntax

try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

Consider the following examples.

try:  
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("c = %d"%c)
    #print("c = ",c)
    #print("c = {}".format(c))
except:  
    print("Can't divide with zero")  

Output:

case 1:

Enter a:10
Enter b:5
c = 2

case :2

Enter a:10
Enter b:0
Can’t divide with zero

We can also use the else statement with the try-except statement in which, we can place the code which will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

Syntax:

try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
    print("a/b = ",c)    
    print("{}/{} = {}".format(a,b,c))
except:
    print("can't divide by zero")    
else:    
    print("Hi I am else block")     

Output:

Case:1
Enter a:10
Enter b:5
a/b = 2
a/b = 2.0
10/5 = 2.0
Hi I am else block

Case:2
Enter a:10
Enter b:0
can’t divide by zero

Visitor Counter

0056707