Lesson 2of 2
Creating Custom Exceptions
Learn how to handle Python errors and exceptions effectively. Fix common Python errors like SyntaxError, TypeError, and NameError with practical examples.
6. Creating Custom Exceptions
- You can create your own exception classes by inheriting from Python's built-in
Exceptionclass.
Example:
class NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
else:
print("Number is valid.")
try:
check_number(-5)
except NegativeNumberError as e:
print(f"Error: {e}")