Raise Custom Errors Exceptions

suggest change

Python 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 ?

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Raise Custom Errors Exceptions:

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve
189 Raise Custom Errors Exceptions