Python Exception Base Classes

PythonProgrammingServer Side Programming

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
    • AssertionError
    • AttributeError
    • BufferError
    • EOFError
    • ImportError
      • ModuleNotFoundError
    • LookupError
      • IndexError
      • KeyError
    • MemoryError
    • NameError
      • UnboundLocalError
    • OSError
      • BlockingIOError
      • ChildProcessError
      • ConnectionError
        • BrokenPipeError
        • ConnectionAbortedError
        • ConnectionRefusedError
        • ConnectionResetError
    • FileExistsError
    • FileNotFoundError
    • InterruptedError
    • IsADirectoryError
    • NotADirectoryError
    • PermissionError
    • ProcessLookupError
    • TimeoutError
  • ReferenceError
  • RuntimeError
    • NotImplementedError
    • RecursionError
  • StopIteration
  • StopAsyncIteration
  • SyntaxError
    • IndentationError
      • TabError
  • SystemError
  • TypeError
  • ValueError
    • UnicodeError
      • UnicodeDecodeError
      • UnicodeEncodeError
      • UnicodeTranslateError
  • Warning
    • BytesWarning
    • DeprecationWarning
    • FutureWarning
    • ImportWarning
    • PendingDeprecationWarning
    • ResourceWarning
    • RuntimeWarning
    • SyntaxWarning
    • UnicodeWarning
    • UserWarning
  • GeneratorExit
  • KeyboardInterrupt
  • SystemExit

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

 Live Demo

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
raja
Published on 30-Oct-2018 13:11:24
Advertisements