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
2
Filter
3
List
7
Loops
16
JSON Module
18
Metaclasses
20
Generators
22
Reduce
23
Map Function
25
Searching
26
Dictionary
27
Classes
28
Counting
31
Set
36
Unit Testing
41
Copying data
42
Tuple
45
Enum
47
Conditionals
48
Complex math
52
Networking
58
HTML Parsing
60
setup.py
61
List slicing
62
Sockets
64
Recursion
66
dis module
67
Type Hints
70
Exceptions
71
Web scraping
72
deque module
75
Overloading
76
Debugging
86
Indentation
89
urllib
90
Binary Data
92
Idioms
98
PostgreSQL
99
Descriptor
100
Common Pitfalls
101
Multiprocessing
104
Stack
105
Profiling
109
Logging
111
os module
113
Database Access
118
Mixins
119
Attribute Access
120
ArcPy
123
Websockets
126
Arrays
128
Polymorphism
132
2to3 tool
135
Unicode
136
ssh in Python
138
Neo4j
140
Curses
141
Templates
142
pass statement
144
Date Formatting
145
heapq
146
tkinter
147
CLI subcommands
149
SQLite3 module
152
Design Patterns
154
Audio
155
pyglet
156
queue module
157
ijson
159
base64 module
160
Flask
161
Groupby
163
pygame
165
hashlib
166
Gzip
167
ctypes
170
configparser
176
Unzipping Files
179
sys module
184
Python Lex-Yacc
185
pyaudio
186
shelve
189
Raise Custom Errors Exceptions
191
Contributors