How to Handle Custom Exceptions

126 views

How to Handle Custom Exceptions

How to Handle Custom Exceptions

How can you create and handle custom exceptions in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

Define a new exception class deriving from Exception.

Code:

class MyCustomError(Exception):
    pass

def myFunction():
    raise MyCustomError("This is a custom exception.")

try:
    myFunction()
except MyCustomError as e:
    print(e)  # Output: This is a custom exception.

solveurit24@gmail.com Changed status to publish February 20, 2025
0