- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
User-defined Exceptions in Python with Examples
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.
# 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
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.
# 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!
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.
# 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.
- Related Articles
- User-Defined Exceptions in Python
- User-defined Exceptions in C# with Example
- What are user-defined exceptions in C#?
- User defined and custom exceptions in Java
- How to create user defined exceptions in C#?
- How to implement user defined exception in Python?
- 2D vector in C++ with user defined size
- User Defined Literals in C++
- Select into a user-defined variable with MySQL
- MySQL ORDER BY with numeric user-defined variable?
- PHP User-defined functions
- User-defined Custom Exception in C#
- Using User-Defined Variables in MySQL
- Set user-defined variable with table name in MySQL prepare statement?
- What is user-defined signal handler?