Try-Except Blocks

try:
    # Risky code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Code to run if a ZeroDivisionError occurs
    print("You can't divide by zero!")
You can't divide by zero!
try:
    # Risky code
    result = int('abc')
except ValueError:
    # Code to run if a ValueError occurs
    print("A value error occurred: invalid literal for int()")
except TypeError:
    # Code to run if a TypeError occurs
    print("A type error occurred.")
A value error occurred: invalid literal for int()
try:
    # Risky code
    result = 10 / 'a'
except (ZeroDivisionError, TypeError, ValueError) as e:
    print(f"An error occurred: {e}")
An error occurred: unsupported operand type(s) for /: 'int' and 'str'
try:
    # Risky code
    result = 10 / 2
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print(f"Division result: {result}")
finally:
    print("Execution completed.")
Division result: 5.0
Execution completed.
try:
    with open('sample.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("The file was not found.")
except IOError:
    print("An I/O error occurred.")
else:
    print("File read successfully.")
finally:
    print("File operation completed.")
The file was not found.
File operation completed.
try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Invalid input! Please enter an integer.")
else:
    print(f"Your age is {age}")
finally:
    print("Input operation completed.")
class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)

def divide(a, b):
    if b == 0:
        raise CustomError("Division by zero is not allowed.")
    return a / b

try:
    result = divide(10, 0)
except CustomError as e:
    print(e)
else:
    print(f"Result: {result}")
finally:
    print("Division operation completed.")
Division by zero is not allowed.
Division operation completed.