Skip to content
On this page

Exception Handling

try-except Blocks:

Exception handling allows you to handle errors gracefully using try-except blocks.

python
# try-except block
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Multiple Exceptions:

You can handle multiple exceptions in a single try-except block.

python
# Multiple exceptions
try:
    result = int("abc")
except ValueError:
    print("Invalid number format.")
except TypeError:
    print("Type mismatch.")

Custom Exceptions:

You can create custom exception classes by inheriting from the Exception class.

python
# Custom exceptions
class MyCustomError(Exception):
    pass

try:
    raise MyCustomError("This is a custom exception.")
except MyCustomError as e:
    print(e)