Python Exceptions

What is exception?

Any unexpected error in your python program, Exception is the base class for all exceptions in python.

What is exception handling?

Exception handling is the power to handle exceptions in the python program.

try/except clause

try block is used to monitor the code which may throw exceptions and except block is used to handle the exception which is thrown in try block.
#!/usr/bin/python                                                               
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    result = a/0                                                                
except ZeroDivisionError as ex:                                                 
    print("Exception: %s" % ex)                                                 
                                                                                
print result  
Output:
$ python exception_test.py 
Exception: integer division or modulo by zero
0

How to raise exception?

raise statement is used to raise the exception.
#!/usr/bin/python                                                               
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    result = a/0                                                                
except ZeroDivisionError as ex:                                                 
    print("Exception: %s" % ex)    
    # raises the same exception using alias name                                        
    raise ex                                                                    
                                                                                
print result                                                                    
Output:
$ python exception_test.py
Exception: integer division or modulo by zero
Traceback (most recent call last):
  File "exception_test.py", line 9, in 
    raise ex
ZeroDivisionError: integer division or modulo by zero
raises exception using corresponding exception class or custom exception.
#!/usr/bin/python                                                               
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    #result = a/0                                                               
    raise ZeroDivisionError("Divide by zero error")                             
except ZeroDivisionError as ex:                                                 
    print("Exception: %s" % ex)                                                 
    #raise ex                                                                   
                                                                                
print result   
Output:
$ python exception_test.py
Exception: Divide by zero error
0

How to handle multiple exceptions?

Multiple exceptions can be handled in single except block with common code or multiple except blocks with different code.

Single except block to handle multiple exceptions

#!/usr/bin/python                                                               
                                                                                
a = [10, 20, 30, 40, 50]                                                        
result = 0                                                                      
try:                                                                            
    result = a[6]/0                                                             
except (IndexError, ZeroDivisionError) as ex:                                   
    print("Exception: %s" % ex)                                                 
                                                                                
print result    
Output:
$ python exception_test1.py 
Exception: list index out of range
0

Multiple except blocks to handle multiple exceptions

#!/usr/bin/python                                                               
                                                                                
a = [10, 20, 30, 40, 50]                                                        
result = 0                                                                      
try:                                                                            
    result = a[6]/0                                                             
except IndexError as ex:                                                        
    print("Index Error: %s" % ex)                                               
                                                                                
except ZeroDivisionError as ex:                                                 
    print("Zero Division Error: %s" % ex)                                       
                                                                                
print result  
Output:
$ python exception_test2.py 
Index Error: list index out of range
0

What is the use of finally clause?

finally clause will run whether or not an exception occurred.
finally clause is mostly used for clean up activities.
#!/usr/bin/python                                                               
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    result = a/0                                                                
except ZeroDivisionError as ex:                                                 
    print("Exception: %s" % ex)                                                 
finally:                                                                        
    print("finally block")                                                      
                                                                                
print result       
Output:
$ python finally_test.py
Exception: integer division or modulo by zero
finally block
0

try/else clause

else block will be executed when no exception is occurred.
#!/usr/bin/python                                                               
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    result = a/10                                                               
except ZeroDivisionError as ex:                                                 
    print("Exception: %s" % ex)                                                 
else:                                                                           
   print("ZeroDivisionError is not occurred")                                   
                                                                                
print result  
Output:
$ python try_else_test.py 
ZeroDivisionError is not occurred
1

Custom Exception

Custom exception can be created by creating subclass for Exception class.
class CustomError(Exception):
    """Custom Failure"""
Example:
#!/usr/bin/python                                                               
      
# Custom exception creation                                                                          
class DivideByZeroError(Exception):                                             
    """Custom Failure"""                                                        
                                                                                
a = 10                                                                          
result = 0                                                                      
try:                                                                            
    #result = a/0    
    # raises custom exception                                                           
    raise DivideByZeroError("Divide by zero error")                             
except DivideByZeroError as ex:                                                 
    print("Exception: %s" % ex)                                                 
    #raise ex                                                                   
                                                                                
print result   
Output:
$ python exception_test.py
Exception: Divide by zero error
0

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^