Updated April 17, 2023
Introduction to Python Throw Exception
The following article provides an outline for Python Throw Exception. Python returns an error or exceptions sometimes when there is no programmatic or syntax mistake in our program, sometimes wrong input also generates an exception like division of two numbers will not return an exception, but the number is divided by zero will return an exception. So we need to do proper exception handling, and we need to detect which part of our program can return an exception, and we can surround that part with the try-catch block and return a proper exception to the user so that he can identify that program arose during program execution.
Raising Exceptions
We can use the raise keyword and name of the exception to forcefully throw an exception by python. We can also pass any message inside the exception or simply write an exception name.
Example #1
Code:
raise NameError("Hello")
Output:
As you can see, python has returned a NameError exception with a Hello message. We can also generate exceptions without any message.
Example #2
Code:
raise NameError
Output:
As you can see, that exception is generated, but it is not good. So we can try to catch this exception and try to display a custom message when such an exception occurs during program execution.
Example #3
Code:
try:
raise NameError('Hello')
except NameError:
print('Sorry Exception is generated')
Output:
In this example, you can see that we have written our code in the try block. We write their piece of code that might return an exception in the try block and catch that exception in a catch block. We have defined the except block and defined the name of the exception that we are looking for. If the program returns that exception, then we return a custom message to the user, and it looks more clean and promising than the default python exception.
User-Defined Exceptions
The user defines these types of exceptions by making class. Generally, exceptions are inherited from the Exception class. This class is very similar to other custom classes that we make in our programs. We can write anything inside these classes, but it’s good to practice to keep it very simple and define only the required attributes or variables or information that will be needed by exception handlers.
Example #1
Code:
class failedException(Exception):
def __init__(self):
super()
try:
marks = 35
print("Your marks are: "+str(marks))
if marks<36:
raise failedException
except failedException:
print("Sorry! You are failed!")
else:
print("Congratulations! You are passed")
Output:
In the above program, you can see that we have defined our class failedException. You can define any name as per your wish. We are inheriting the exception class. We have defined inside it and used the constructor; we call base class methods, i.e. super(). We have created a try block, and then we have defined a variable mark with a value of 35. First, we are just printing the message and value of the variable. Then we are checking if the value is less than 36, then we are raising the exception.
We can write any name for the exception as it is user-defined. Then we have defined except that is catching our exception and printing defined message and in else condition, we have defined another message. When our condition is failed, then our defined exception is called, and a message is printed.
Example #2
Code:
class MarksRange(Exception):
def __init__(self, marks, message="You are failed!"):
self.marks = marks
self.message = message
super().__init__(self.message)
def __str__(self):
return f'{self.marks} -> {self.message}'
marks = int(input("Enter marks: "))
if not marks > 36:
raise MarksRange(marks)
Output:
In this above program, we have created a custom class MarksRange and inherited the Base Class Exception.
We have defined a constructor inside the class and passed self, marks, and message variables that are holding our values. We are overriding our constructor with our custom arguments, i.e. marks and messages. We are manually calling the exception of the parent class with self-parameter marks and messages using super().
We are using __str__ for displaying the exception of the class and the message we have defined, and our exception MarksRange will be raised. Python will ask the user to input the marks then check if the marks are less than 36. If the condition matches, then we are raising the exception; if the condition doest match, nothing will happen. When we are creating a large python program, it is always a good practice to keep custom user-defined exceptions in a separate file; it’s a kind of standard process that is followed. We can name our exception file as exception.py or error.py also.
Conclusion – Python Throw Exception
User-Defined exceptions are the exceptions that the user defines to handle some error scenario that is not inbuilt. We want to make custom exceptions and show them accordingly to the user end.
Recommended Articles
This is a guide to Python Throw Exception. Here we discuss the introduction, raising, and user-defined exceptions along with examples respectively. You may also have a look at the following articles to learn more –