How To Use User Defined Exception In Python

Python provides a lot of built-in exception classes. All the built-in classes are sub-class of builtins.BaseException class. Besides the built-in exception class, you can also create customize exception classes. But all custom exception classes must extend builtins.Exception class. The builtins.Exception class is also a sub-class of builtins.BaseException class. This example will tell you how to define a custom python exception class and how to use it.

1. Create Custom Python Exception Class Example.

  1. Create a PyDev project and a python package and a module com.dev2qa.example.exception.CustomException.py.(  You can refer article How To Run Python In Eclipse With PyDev )
  2. Now edit the CustomException.py module file, and copy the below source code into it.
    '''
    Created on Jan 3, 2020
    
    @author: songzhao
    '''
    from builtins import Exception
    
    # The custom exception need to extend 
    class CustomException(Exception):
        
        def __init__(self, *params):
            
            if len(params) > 0:
                
                self.exception_message = params[0]
            
        
        def __str__(self):
            return 'This is a customized exception class, the error message is :' + self.exception_message
        
        
    # This function will raise exception by the input parameter value.
    # The input parameter is a boolean value. 
    def test_exception(ThrowCustomException):
        
        try:
            
            if(ThrowCustomException):
            
                # Raise an instance of CustomException class. 
                raise CustomException('This exception is created and threw in try block.', 'hello')
         
            else:
                # Below code will raise a ZeroDivisionError error.
                a = 1 / 0
                
        except CustomException as e:
                
                print('Exception class name : ', e.__class__.__name__)
                
                print('Exception data : ', e)       
        
        except ZeroDivisionError as e:
                
                print('Exception class name : ', e.__class__.__name__)
                
                print('Exception data : ', e)            
                
        finally:
                
                print('The example run complete.\n')            
                    
            
    if __name__ == '__main__':
        
        # Test system built-in exception.
        test_exception(False)
        
        # Test customize exception.
        test_exception(True)
    
  3. Right-click the python source code, and click Run As —> Python Run menu item, then you can get the below output in the console. The first error is a system built-in error ZeroDivisionError. The second error is the CustomException error.
    Exception class name :  ZeroDivisionError
    Exception data :  division by zero
    The example run complete.
    
    Exception class name :  CustomException
    Exception data :  This is a customized exception class, the error message is :This exception is created and threw in try block.
    The example run complete.
    
    

Subscribe to receive more programming tricks.

We don’t spam!

Subscribe to receive more programming tricks.

We don’t spam!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.