All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Python Raise Custom Exception

Last Updated : Mar 11, 2024

Python Raise Custom Exception

In this article we will show you the solution of python raise custom exception, using examples, we will learn in this course how to define unique exceptions that meet our specific needs. We learnt about the many built-in exceptions available in Python in the previous session, as well as the significance of handling exceptions.

But occasionally we might need to make our own special exclusions to suit our needs.

By deriving a new class from the default Exception class in Python, we can define our own exception types.

You must specify a class that derives from the built-in Exception class or one of its subclasses, such as ValueError, in order to construct a custom exception class.

We will now discuss the idea of how to raise custom exceptions with an example.

Step By Step Guide On Python Raise Custom Exception :-

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 {self.f} is not in a valid range {self.min_f, self.max_f}'
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'{f} Fahrenheit = {c:.4f} Celsius')
  1. FahrenheitError is the name of the unique exception class we create.
  2. The valid range of Fahrenheit temperatures is represented by the class variables min_f and max_f of the FahrenheitError class.
  3. The constructor of the parent class receives a temperature in Fahrenheit along with any other arguments from the FahrenheitError class' init function.
  4. The invalid Fahrenheit temperature and the acceptable range are included in the string representation of the exception that is returned by the FahrenheitError class's str function.
  5. A Fahrenheit temperature is inputted into the fahrenheit_to_celsius function, which converts it to Celsius. If the input temperature is outside of the acceptable range of Fahrenheit temperatures, a FahrenheitError is raised.
  6. We request a temperature in Fahrenheit from the user in the main block, and then try to convert it to a float using a try-except block. A ValueError is raised and the error message is printed if the user enters a non-numeric value.
  7. Another try-except block is used to pass the input to the fahrenheit_to_celsius function if it is valid. We print the error message if a FahrenheitError is raised. Otherwise, we display the temperature in Celsius after conversion.

Conclusion :-

As a result, we have successfully learned how to raise custom exceptions with an example.

To create a unique exception class, subclass the Exception class or one of its subclasses.

I hope this article on python raise custom exception helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪