. Advertisement .
..3..
. Advertisement .
..4..
Exceptions are a particular kind of occurrence that takes place whenever a program encounters a situation that doesn’t proceed as planned. Want to learn how to construct a Python custom exception? This guide will show you how.
Create A Python Custom Exception Class
In Python, the exception class can be created in the same manner as the regular class. The primary distinction is that you must include the base class Exception of Python in order to tell your compiler that the class you are creating is indeed an exception one.
Let’s try out this way by developing an exception type named DemoException and utilizing the placeholder control pass flow keyword within as a stand-in.
class DemoException(Exception):
pass
Implement Exception-Raising Utilizing The raise Keyword
Raise exceptions to examine the class DemoException’s output when it is actually called in other programming languages. Notice that in other programming languages, raising exceptions is referred to as throwing exceptions.
With the help of the raise keyword, you can cause an exception with the specified exception class and produce a message of the exception.
class DemoException(Exception):
pass
raise DemoException
Output:
Traceback (most recent call last):
File "/Users/demo/python/demo_exception.py", line 4, in <module>
raise DemoException
__main__.DemoException
Suppose there is no stated custom exception message; the standard exception will appear as in the terminal.
Declare A Python Custom Exception Message
In order to declare the class DemoException’s custom exception message, override the approach __init__()
of the class and take in the custom message with the required self-referential argument self.
For instance, let’s write a message DemoException and override the method __init__()
.
class DemoException(Exception):
def __init__(self, message):
super().__init__(message)
Be aware that you must call the basic class Exception; the function __init__()
with the argument message if you want your message to merge into the exception effectively.
Here, we use the keyword raise to call our exception class once more and then pass a custom message along with it.
class DemoException(Exception):
def __init__(self, message):
super().__init__(message)
message = "Exception Triggered! Something went wrong."
raise DemoException(message)
Output:
Traceback (most recent call last):
File "/Users/demo/python/helloworld.py", line 6, in <module>
raise DemoException(message)
__main__.DemoException: Exception Triggered! Something went wrong.
As you can see, the exception class with the custom error message is successfully constructed.
Implement Exception-Handling Utilizing The Block try…except
You can handle and throw exceptions neatly utilizing the block try…except
. This block is quite similar to the block try-catch
in the Java programming language.
There are two mandatory and two optional one in try…except.
- try – mandatory: This is the primary block in charge of enclosing the code in which the exception may be triggered. It stops the entire process anytime an exception is raised.
- except – mandatory: It proceeds when a specific exception is raised. Usually, a print() command or a detailed error message for a caller is contained in this block. One block try may contain many blocks except, each of which would capture a distinct exception.
- else – optional: If no exceptions were thrown by the block try, the program would move on to this block else.
- finally – optional: After the first three blocks have been completed, regardless of whether an exception was raised, the block finally still executes.
To test the block try…except, utilize the class DemoException from the preceding example.
Wrap the keyword raise within a function, then place it in the block try…except. For this example, we will write a function that takes in a number and raises an exception if the value sent is 0. Notice that any other number will cause the code to function as intended.
Here is an example.
class DemoException(Exception):
def __init__(self, message):
super().__init__(message)
message = "Exception Triggered! Something went wrong."
def triggerException(num):
if (num == 0):
raise DemoException(message)
else:
print(num)
try:
triggerException(0)
print("Code has successfully been executed.")
except DemoException:
print("Error: Number should not be 0.")
Since triggerException()
passed the 0 value as a parameter, DemoException should be triggered. In this case, we should anticipate that the output of the keyword message raise will be replaced by whatever is contained in the block except.
Keep in mind that the line print()
after the function triggerException()
wasn’t outputted. It happened because the method produced an exception, which immediately caused it to stop all processes inside the block try and jump right to the block except.
Output:
Error: Number should not be 0.
Let’s now attempt passing a legitimate number, such as 20, for instance.
try:
triggerException(20)
print("Code has successfully been executed.")
except DemoException:
print("Error: Number should not be 0.")
Output:
20
Code has successfully been executed.
Attempting to chain multiple blocks expect will result in another exception. Here, call NumberFormatException as it only occurs when the input isn’t a number. Declare a message inside this exception class.
class NumberFormatException(Exception, value):
message = f‘{value} is not a number’
def __init__(self):
super().__init__(message)
In order to handle the NumberFormatException
class, change the code above as follows:
class DemoException(Exception):
def __init__(self, message):
super().__init__(message)
class NumberFormatException(Exception):
def __init__(self, message, value):
message = f‘{value} is not a number’
super().__init__(message)
message = "Exception occured."
def triggerException(num):
if (not num.isdigit()):
raise NumberFormatException(message, num)
elif (num == 0):
raise DemoException(message)
else:
print(num)
num = "sample string"
try:
triggerException(num)
print("Code has successfully been executed.")
except DemoException:
print("Error: Number should not be 0.")
except NumberFormatException:
print(num+" is not a number.")
As you can see, the NumberFormatException class ought to be raised as the num value passed to the triggerException()
function is a ‘sample string’ string.
Output:
sample string is not a number.
The Bottom Line
Now you know how to create a Python custom exception. Hopefully, you will find this guide useful and easy to comprehend.
Suppose you encounter a KeyError: 0 exception while working with Python; check out this tutorial to fix the problem.
Leave a comment