Python Exception Base Classes
Like other high-level languages, there are some exceptions in python also. When a problem occurs, it raises an exception. There are different kind of exceptions like ZeroDivisionError, AssertionError etc. All exception classes are derived from the BaseException class.
The code can run built in exceptions, or we can also raise these exceptions in the code. User can derive their own exception from the Exception class, or from any other child class of Exception class.
The BaseException is the base class of all other exceptions. User defined classes cannot be directly derived from this class, to derive user defied class, we need to use Exception class.
The Python Exception Hierarchy is like below.
- BaseException
- Exception
- ArithmeticError
- FloatingPointError
- OverflowError
- ZeroDivisionError
- ModuleNotFoundError
- IndexError
- KeyError
- UnboundLocalError
- BlockingIOError
- ChildProcessError
- ConnectionError
- BrokenPipeError
- ConnectionAbortedError
- ConnectionRefusedError
- ConnectionResetError
- NotImplementedError
- RecursionError
- IndentationError
- TabError
- UnicodeError
- UnicodeDecodeError
- UnicodeEncodeError
- UnicodeTranslateError
- BytesWarning
- DeprecationWarning
- FutureWarning
- ImportWarning
- PendingDeprecationWarning
- ResourceWarning
- RuntimeWarning
- SyntaxWarning
- UnicodeWarning
- UserWarning
Problem − In this problem there is a class of employees. The condition is, the age of employee must be greater than 18.
We should create one user defined exception class, which is a child class of the Exception class.
Example Code
class LowAgeError(Exception): def __init__(self): pass def __str__(self): return 'The age must be greater than 18 years' class Employee: def __init__(self, name, age): self.name = name if age < 18: raise LowAgeError else: self.age = age def display(self): print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years') try: e1 = Employee('Subhas', 25) e1.display() e2 = Employee('Anupam', 12) e1.display() except LowAgeError as e: print('Error Occurred: ' + str(e))
Output
The name of the employee: Subhas, Age: 25 Years Error OccurredThe age must be greater than 18 years
- ArithmeticError