- Python Custom Exceptions
- Raise Exceptions
- Defining Custom Exceptions
- 1. Create a Custom Exception Class
- 2. Add a custom Message and Error
- Conclusion
- References
- Python raise exception with custom message | Manually raising
- Syntax
- Python raises exception Example:
- Let’s see Another Example
- QA: How to raise an exception in Python 3
- Reference :
Python Custom Exceptions
An Exception is raised whenever there is an error encountered, and it signifies that something went wrong with the program. By default, there are many exceptions that the language defines for us, such as TypeError when the wrong type is passed. In this article, we shall look at how we can create our own Custom Exceptions in Python.
But before we take a look at how custom exceptions are implemented, let us find out how we could raise different types of exceptions in Python.
Raise Exceptions
Python allows the programmer to raise an Exception manually using the raise keyword.
Format: raise ExceptionName
The below function raises different exceptions depending on the input passed to the function.
def exception_raiser(string): if isinstance(string, int): raise ValueError elif isinstance(string, str): raise IndexError else: raise TypeError
>>> exception_raiser(123) Traceback (most recent call last): File "", line 1, in File "", line 3, in exception_raiser ValueError >>> exception_raiser('abc') Traceback (most recent call last): File "", line 1, in File "", line 5, in exception_raiser IndexError >>> exception_raiser([123, 456]) Traceback (most recent call last): File "", line 1, in File "", line 7, in exception_raiser TypeError
As you can observe, different types of Exceptions are raised based on the input, at the programmer’s choice. This allows for good flexibility of Error Handling as well, since we can actively predict why an Exception can be raised.
Defining Custom Exceptions
Similarly, Python also allows us to define our own custom Exceptions. We are in complete control of what this Exception can do, and when it can be raised, using the raise keyword. Let us look at how we can define and implement some custom Exceptions.
1. Create a Custom Exception Class
We can create a custom Exception class to define the new Exception. Again, the idea behind using a Class is because Python treats everything as a Class. So it doesn’t seem that outlandish that an Exception can be a class as well!
All Exceptions inherit the parent Exception Class, which we shall also inherit when creating our class.
We shall create a Class called MyException , which raises an Exception only if the input passed to it is a list and the number of elements in the list is odd.
class MyException(Exception): pass def list_check(lst): if len(lst) % 2 != 0: raise MyException # MyException will not be raised list_check([1, 2, 3, 4]) # MyException will be raised list_check([1, 3, 5])
[email protected]:~# python3 exceptions.py Traceback (most recent call last): File "exceptions.py", line 12, in list_check([1, 3, 5]) File "exceptions.py", line 6, in list_check raise MyException __main__.MyException
2. Add a custom Message and Error
We can add our own error messages and print them to the console for our Custom Exception. This involves passing two other parameters in our MyException class, the message and error parameters.
Let us modify our original code to account for a custom Message and Error for our Exception.
class MyException(Exception): def __init__(self, message, errors): # Call Exception.__init__(message) # to use the same Message header as the parent class super().__init__(message) self.errors = errors # Display the errors print('Printing Errors:') print(errors) def list_check(lst): if len(lst) % 2 != 0: raise MyException('Custom Message', 'Custom Error') # MyException will not be raised list_check([1, 2, 3, 4]) # MyException will be raised list_check([1, 3, 5])
Printing Errors: Custom Error Traceback (most recent call last): File "exceptions.py", line 17, in list_check([1, 3, 5]) File "exceptions.py", line 11, in list_check raise MyException('Custom Message', 'Custom Error') __main__.MyException: Custom Message
We have thus successfully implemented our own Custom Exceptions, including adding custom error messages for debugging purposes! This can be very useful if you are building a Library/API and another programmer wants to know what exactly went wrong when the custom Exception is raised.
Conclusion
In this article, we learned how to raise Exceptions using the raise keyword, and also build our own Exceptions using a Class and add error messages to our Exception.
References
Python raise exception with custom message | Manually raising
If you want to set up manually python exception then you can do it in Python. Python raise exception is the settlement to throw a manual error.
It’s always suggestible Don’t raise generic exceptions. Learn about Generic exception must read this tutorial – Python exception Handling | Error Handling
Syntax
In Python 3 there are 4 different syntaxes of raising exceptions.
- raise exception – No argument print system default message
- raise exception (args) – with an argument to be printed
- raise – without any arguments re-raises the last exception
- raise exception (args) from original_exception – contain the details of the original exception
raise ValueError('I am erorr')
In this tutorial, we used raise exception(args) to raise an exception. The args will be print by exception object.
Python raises exception Example:
It’s a simple example for raise exceptions with a custom message. The sole argument to raise shows the exception to be raised.
try: raise NameError('HiThere') except NameError: print('An raise exception !') raise
Let’s see Another Example
If you want an throwing error on any condition, like if negative values have entered. So you can do it like that example.
try: a = int(input("Enter a positive Number: ")) if a
QA: How to raise an exception in Python 3
it can be your interview question. There is simply you have to write an raise exception(args) in try except block, same as upper examples.
Reference :
Bonus: this tutorial is not cover the exception and error handling, for that you must follow this tutorial.
Do comment if you have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All examples are of raise exception in python 3, so it may change its different from python 2 or upgraded versions.