User-defined Exceptions in Python with Examples

PythonServer Side ProgrammingProgramming

Python throws errors and exceptions whenever code behaves abnormally & its execution stop abruptly. Python provides us tools to handle such scenarios by the help of exception handling method using try-except statements. Some standard exceptions which are found are include ArithmeticError, AssertionError, AttributeError, ImportError, etc.

Creating a User-defined Exception class

Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class.

Example

 Live Demo

# class MyError is extended from super class Exception
class User_Error(Exception):
   # Constructor method
   def __init__(self, value):
      self.value = value
   # __str__ display function
   def __str__(self):
      return(repr(self.value))
try:
   raise(User_Error("User defined error"))
   # Value of Exception is stored in error
except User_Error as error:
   print('A New Exception occured:',error.value)

Output

A New Exception occured: User defined error

Creating a User-defined Exception class (Multiple Inheritance)

Derived class Exceptions are created when a single module handles multiple several distinct errors. Here we created a base class for exceptions defined by that module. This base class is inherited by various user-defined class to handle different types of errors.

Example

 Live Demo

# define Python user-defined exceptions
class Error(Exception):
   """Base class for other exceptions"""
   pass
class Dividebyzero(Error):
   """Raised when the input value is zero"""
   pass
try:
   i_num = int(input("Enter a number: "))
   if i_num ==0:
      raise Dividebyzero
except Dividebyzero:
   print("Input value is zero, try again!")
   print()

Output

Enter a number: Input value is zero, try again!

Creating a User-defined Exception class (standard Exceptions)

Runtime error is a built-in class which is raised whenever a generated error does not fall into mentioned categories. The program below explains how to use runtime error as base class and user-defined error as derived class.

Example

 Live Demo

# User defined error
class Usererror(RuntimeError):
   def __init__(self, arg):
      self.args = arg
try:
   raise Usererror("userError")
except Usererror as e:
   print (e.args)

Output

('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')

Conclusion

In this article, we learnt how we declare and implement user-defined exceptions in Python 3.x. Or earlier.

raja
Published on 29-Aug-2019 11:10:43
Advertisements