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

If we do not use handling exceptions handling

As we know that an exception is an abnormal condition that halts the execution of the program.
Suppose, we take input for two variables a and b, and perform the division of these values.
What if the user entered the zero as the denominator?
It will interrupt the program execution and through a ZeroDivision exception.


a = int(input("Enter a:"))    
b = int(input("Enter b:"))    
c = a/b  
print("a/b = %d" %c)    
#other code:    
print("This will get executed if there is no error")  

case 1:

Enter a:10
Enter b:5
a/b = 2
This will get executed if there is no erro

case 2:
Enter a:10
Enter b:0
Traceback (most recent call last):
File “E:\batch79\hello\”, line 3, in <module>
c = a/b
ZeroDivisionError: division by zero

The above program is syntactically correct, but it through the error because of unusual input. That kind of programming may not be suitable or recommended for the projects because these projects are required uninterrupted execution. That’s why an exception-handling plays an essential role in handling these unexpected exceptions.

Visitor Counter