DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

1

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):
    pass


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.

Output:
Traceback (most recent call last):  
File ".\main.py", 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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more