DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Python Custom Exception

Create Custom Exception In Python

As you have heard, Everything is an object in python. An Exception is also a class in python.

We can create an exception in python by inheriting the in-built class Exception in Python.

Let’s make our custom exception, which will raise an error when it encounters a number in a string. The Name of the Exception class will be NumberInStringException.

The name is long, but it explains the exception. You don’t need to know Object-Oriented programming in python in order to understand this concept. Stick with it and you will learn everything.

class NumberInStringException(Exception):

word = "HackTheDeveloper17"
for c in word:
    if c.isdigit():
        raise NumberInStringException(c)
Enter fullscreen mode Exit fullscreen mode

In the above code, we defined a class with the name NumberInStringException which inherits the inbuilt python class Exception, which provides our class the Exception features. There is no code in the class, just the pass statement.

Next, we defined a loop that checks for any number in the string value. If the character is a number the custom exception is raised.

Traceback (most recent call last):  
File ".\", line 8, in <module>
    raise NumberInStringException(c)
__main__.NumberInStringException: 1 
Enter fullscreen mode Exit fullscreen mode

Read the whole post Python Custom Exception from the original Post.

Top comments (0)