Mar 18, 2013

Python User Defined Exceptions


Today we discuss about raising exceptions manually (Python User Defined Exceptions).

1) We already know we have built in exceptions in Python like ValueError, IOError, FileNotFoundError, ZeroDivisionError

2) But sometimes we might have to write custom exceptions on our own to catch few scenarios.

Lets discuss how to implement user defined exception with an example.

In the below example :

nonEmptyValException                                  #User Defined Exception

ValueError, ZeroDivisionError, EOFError   #Built-in Exceptions


exceptions_raise_manual.py
import sys

class nonEmptyValException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, num):
        Exception.__init__(self)
        self.num = num
      
try:
    a = int(input('Enter some integer for Dividend --> '))
    b = int(input('Enter some integer for Divisor --> '))
    
    if not a:
       raise nonEmptyValException(a)
       
    if not b:
       raise nonEmptyValException(b)
    
    c = a/b;    

    print ("Final Value is : ", c) 
    
except  ValueError:
    print('ValueError: Please enter only Integer Value')   
except ZeroDivisionError:
    print('ZeroDivisionError: The input divisor is %d, was expecting a Non-Zero number' % (b))   
except EOFError:
    print('\nWhy did you do an EOF on me?')
except nonEmptyValException as error:
    print('nonEmptyValException: The input is %d, was expecting a integer number' % (error.num))  


Please refer to other Python Exceptions Concepts :
All Python Exceptions Related Topics
Exceptions in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton



No comments:

Post a Comment