Try-except Blocks

Here are four code examples that demonstrate how to use try-except blocks in Python to handle exceptions.

  1. Handling a ValueError Exception

The following code demonstrates how to handle a ValueError exception that is raised when a string is passed to the int() function instead of an integer. The try-except block catches the ValueError exception and prints a custom error message:

try:
    number = int(input("Enter an integer: "))
except ValueError:
    print("Error: You did not enter an integer. Please try again.")
  1. Handling Multiple Exceptions

The following code demonstrates how to handle multiple exceptions using multiple except clauses. In this example, the try clause raises a ZeroDivisionError exception when dividing by zero and a TypeError exception when trying to divide a string by an integer. The except clauses handle both exceptions and print custom error messages:

try:
    numerator = int(input("Enter the numerator: "))
    denominator = int(input("Enter the denominator: "))
    result = numerator / denominator
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
except TypeError:
    print("Error: Numerator and denominator must be integers.")
  1. Using the else Clause

The following code demonstrates how to use the else clause in a try-except block. In this example, the try clause attempts to open a file and read its contents. If the file is successfully opened and read, the contents are printed to the screen. If an exception is raised, the except clause catches the exception and prints an error message:

try:
    with open("file.txt", "r") as file:
        contents = file.read()
except FileNotFoundError:
    print("Error: File not found.")
else:
    print("File contents:")
    print(contents)
  1. Using the finally Clause

The following code demonstrates how to use the finally clause in a try-except block. In this example, the try clause attempts to open a file and read its contents. The finally clause is used to close the file regardless of whether an exception is raised or not:

try:
    with open("file.txt", "r") as file:
        contents = file.read()
except FileNotFoundError:
    print("Error: File not found.")
finally:
    file.close()

These code examples demonstrate the basic concepts of exception handling in Python using try-except blocks. You can use these examples as a starting point for handling exceptions in your own programs.