Skip to content
Python

Exception Handling

Complete exception handling mechanism.

By EZ4Code Team
exceptionerror

Code

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Division by zero error: {e}")
except (TypeError, ValueError) as e:
    print(f"Type or value error: {e}")
except Exception as e:
    print(f"Other error: {e}")
else:
    print(f"Success: {result}")
finally:
    print("Always executes")

# Custom exception
class AppError(Exception):
    def __init__(self, code, message):
        self.code = code
        super().__init__(message)

# Raise exception
raise AppError(500, "Server error")

Explanation

try/except/else/finally fully catches exceptions; custom exception classes are supported.

More Python Snippets