Handling Custom Exceptions
Custom exceptions can be handled similar to built-in exceptions using a `try…except` block.
try:
result = divide(10, 0)
except MyCustomError as e:
print(f"Caught an error: {e}")
Here divide function raises `MyCustomError` and it is caught and handled by the `except` block. Additional attributes and methods can be used to enhance Custom Exceptions to provide more context or functionality.
class FileProcessingError(Exception):
def __init__(self, message, filename, lineno):
super().__init__(message)
self.filename = filename
self.lineno = lineno
def __str__(self):
return f"{self.message} in {self.filename} at line {self.lineno}"
try:
raise FileProcessingError("Syntax error", "example.txt", 13)
except FileProcessingError as e:
print(f"Caught an error: {e}")
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the program’s instructions. When an error occurs, Python raises an exception, which can be caught and handled using try
and except
blocks. Here’s a simple example of handling a built-in exception:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
In this example, ZeroDivisionError
is a built-in exception that gets raised when you attempt to divide by zero.
Contact Us