- User-defined Exceptions in Python with Examples
- User-Defined Exception in Python
- Python3
- Customizing Exception Classes
- Python3
- Example 1: User-Defined class with Multiple Inheritance
- Python3
- Example 2: Deriving Error from Super Class Exception
- Python Custom Exception
- Introduction to the Python custom exception
- Python custom exception example
- Define the FahrenheitError custom exception class
- Define the fahrenheit_to_celsius function
- Create the main program
- Put it all together
- Summary
User-defined Exceptions in Python with Examples
In this article, we will try to cover How to Define Custom Exceptions in Python with Examples.
class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python
Python throws errors and exceptions when the code goes wrong, which may cause the program to stop abruptly. Python also provides an exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError.
User-Defined Exception in Python
Exceptions need to be derived from the Exception class, either directly or indirectly. Although not mandatory, most of the exceptions are named as names that end in “Error” similar to the naming of the standard exceptions in python. For example,
Python3
A New Exception occurred: 6
Customizing Exception Classes
To know more about class Exception, run the code below
Python3
Help on class Exception in module exceptions: class Exception(BaseException) | Common base class for all non-exit exceptions. | | Method resolution order: | Exception | BaseException | __builtin__.object | | Methods defined here: | | __init__(. ) | x.__init__(. ) initializes x; see help(type(x)) for signature | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = | T.__new__(S, . ) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from BaseException: | | __delattr__(. ) | x.__delattr__('name') del x.name | | __getattribute__(. ) | x.__getattribute__('name') x.name | | __getitem__(. ) | x.__getitem__(y) x[y] | | __getslice__(. ) | x.__getslice__(i, j) x[i:j] | | Use of negative indices is not supported. | | __reduce__(. ) | | __repr__(. ) | x.__repr__() repr(x) | | __setattr__(. ) | x.__setattr__('name', value) x.name = value | | __setstate__(. ) | | __str__(. ) | x.__str__() str(x) | | __unicode__(. ) | | ---------------------------------------------------------------------- | Data descriptors inherited from BaseException: | | __dict__ | | args | | message
Example 1: User-Defined class with Multiple Inheritance
In the below article, we have created a class named “Error” derived from the class Exception. This base class is inherited by various user-defined classes to handle different types of python raise an exception with message
Python3
Enter a number: 0 Input value is zero, try again!
Example 2: Deriving Error from Super Class Exception
Superclass Exceptions are created when a module needs to handle several distinct errors. One of the common ways of doing this is to create a base class for exceptions defined by that module. Further, various subclasses are defined to create specific exception classes for different error conditions.
Python Custom Exception
Summary: in this tutorial, you’ll learn how to define Python custom exception classes.
Introduction to the Python custom exception
To create a custom exception class, you define a class that inherits from the built-in Exception class or one of its subclasses such as ValueError class:
The following example defines a CustomException class that inherits from the Exception class:
class CustomException(Exception): """ my custom exception class """
Code language: Python (python)
Note that the CustomException class has a docstring that behaves like a statement. Therefore, you don’t need to add the pass statement to make the syntax valid.
To raise the CustomException, you use the raise statement. For example, the following uses the raise statement to raise the CustomException :
class CustomException(Exception): """ my custom exception class """ try: raise CustomException('This is my custom exception') except CustomException as ex: print(ex)
Code language: Python (python)
This is my custom exception
Code language: Python (python)
Like standard exception classes, custom exceptions are also classes. Hence, you can add functionality to the custom exception classes like:
- Adding attributes and properties.
- Adding methods e.g., log the exception, format the output, etc.
- Overriding the __str__ and __repr__ methods
- And doing anything else that you can do with regular classes.
In practice, you’ll want to keep the custom exceptions organized by creating a custom exception hierarchy. The custom exception hierarchy allows you to catch exceptions at multiple levels, like the standard exception classes.
Python custom exception example
Suppose you need to develop a program that converts a temperature from Fahrenheit to Celsius.
The minimum and maximum values of a temperature in Fahrenheit are 32 and 212. If users enter a value that is not in this range, you want to raise a custom exception e.g., FahrenheitError .
Define the FahrenheitError custom exception class
The following defines the FahrenheitError exception class:
class FahrenheitError(Exception): min_f = 32 max_f = 212 def __init__(self, f, *args): super().__init__(args) self.f = f def __str__(self): return f'The is not in a valid range '
Code language: Python (python)
- First, define the FahrenheitError class that inherits from the Exception class.
- Second, add two class attributes min_f and max_f that represent the minimum and maximum Fahrenheit values.
- Third, define the __init__ method that accepts a Fahrenheit value ( f ) and a number of position arguments ( *args ). In the __init__ method, call the __init__ method of the base class. Also, assign the f argument to the f instance attribute.
- Finally, override the __str__ method to return a custom string representation of the class instance.
Define the fahrenheit_to_celsius function
The following defines the fahrenheit_to_celsius function that accepts a temperature in Fahrenheit and returns a temperature in Celcius:
def fahrenheit_to_celsius(f: float) -> float: if f < FahrenheitError.min_f or f > FahrenheitError.max_f: raise FahrenheitError(f) return (f - 32) * 5 / 9
Code language: Python (python)
The fahrenheit_to_celsius function raises the FahrenheitError excpetion if the input temperature is not in the valid range. Otherwise, it converts the temperature from Fahrenheit to Celcius.
Create the main program
The following main program uses the fahrenheit_to_celsius function and the FahrenheitError custom exception class:
if __name__ == '__main__': f = input('Enter a temperature in Fahrenheit:') try: f = float(f) except ValueError as ex: print(ex) else: try: c = fahrenheit_to_celsius(float(f)) except FahrenheitError as ex: print(ex) else: print(f' Fahrenheit = .4f> Celsius')
Code language: Python (python)
First, prompt users for a temperature in Fahrenheit.
f = input('Enter a temperature in Fahrenheit:')
Code language: Python (python)
Second, convert the input value into a float. If the float() cannot convert the input value, the program will raise a ValueError exception. In this case, it displays the error message from the ValueError exception:
try: f = float(f) # . except ValueError as ex: print(ex)
Code language: Python (python)
Third, convert the temperature to Celsius by calling the fahrenheit_to_celsius function and print the error message if the input value is not a valid Fahrenheit value:
try: c = fahrenheit_to_celsius(float(f)) except FahrenheitError as ex: print(ex) else: print(f' Fahrenheit = .4f> Celsius')
Code language: Python (python)
Put it all together
class FahrenheitError(Exception): min_f = 32 max_f = 212 def __init__(self, f, *args): super().__init__(args) self.f = f def __str__(self): return f'The is not in a valid range ' def fahrenheit_to_celsius(f: float) -> float: if f < FahrenheitError.min_f or f > FahrenheitError.max_f: raise FahrenheitError(f) return (f - 32) * 5 / 9 if __name__ == '__main__': f = input('Enter a temperature in Fahrenheit:') try: f = float(f) except ValueError as ex: print(ex) else: try: c = fahrenheit_to_celsius(float(f)) except FahrenheitError as ex: print(ex) else: print(f' Fahrenheit = .4f> Celsius')
Code language: Python (python)
Summary
- Subclass the Exception class or one of its subclasses to define a custom exception class.
- Create a exception class hierarchy to make the exception classes more organized and catch exceptions at multiple levels.