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.
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.
# 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)
A New Exception occured: User defined error
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.
# 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()
Enter a number: Input value is zero, try again!
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.
# User defined error class Usererror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Usererror("userError") except Usererror as e: print (e.args)
('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')
In this article, we learnt how we declare and implement user-defined exceptions in Python 3.x. Or earlier.