Raise Custom Errors Exceptions:
Raise Custom Errors Exceptions
suggest changePython has many built-in exceptions which force your program to output an error when something in it goes wrong.
However, sometimes you may need to create custom exceptions that serve your purpose.
In Python, users can define such exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are also derived from this class.
Custom Exception
Here, we have created a user-defined exception called CustomError which is derived from the Exception class. This new exception can be raised, like other exceptions, using the raise statement with an optional error message.
class CustomError(Exception):
pass
x = 1
if x == 1:
raise CustomError('This is custom error')
Output:
Traceback (most recent call last):
File "error_custom.py", line 8, in <module>
raise CustomError('This is custom error')
__main__.CustomError: This is custom error
Catch custom Exception
This example shows how to catch custom Exception
class CustomError(Exception):
pass
try:
raise CustomError('Can you catch me ?')
except CustomError as e:
print ('Caught CustomError :{}'.format(e))
except Exception as e:
print ('Generic exception: {}'.format(e))
Output:
Caught CustomError :Can you catch me ?
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
3List
22Reduce
27Classes
28Counting
31Set
42Tuple
45Enum
60setup.py
62Sockets
89urllib
92Idioms
104Stack
105Profiling
109Logging
111os module
118Mixins
120ArcPy
123Websockets
126Arrays
128Polymorphism
1322to3 tool
135Unicode
138Neo4j
140Curses
141Templates
145heapq
146tkinter
154Audio
155pyglet
156queue module
157ijson
160Flask
161Groupby
163pygame
165hashlib
166Gzip
167ctypes
170configparser
179sys module
185pyaudio
186shelve
189Raise Custom Errors Exceptions
191Contributors