Error Handling using Try catch in Python

Code Explanation


 try:

    # Code that might raise an error
    result = 10 / 0
except Exception as e:
    # Print the error message
    print(f"An error occurred: {e}")

The Try-Except Block

The most basic form of error handling uses try and except.

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

Instead of crashing, the program catches the exception and displays a meaningful message.


Handling Multiple Exceptions

A single block of code may raise different types of exceptions.

try:
    num = int(input("Enter a number: "))
    result = 100 / num

except ValueError:
    print("Please enter a valid number.")

except ZeroDivisionError:
    print("Division by zero is not allowed.")

This approach allows specific handling for different error scenarios.


Using the Else Block

The else block executes only when no exception occurs.

try:
    num = int(input("Enter a number: "))
    result = 100 / num

except Exception as e:
    print("Error:", e)

else:
    print("Result:", result)

This helps separate successful execution logic from error-handling logic.


Using the Finally Block

The finally block always executes, regardless of whether an exception occurs.

try:
    file = open("data.txt")

except FileNotFoundError:
    print("File not found.")

finally:
    print("Closing resources.")

This is especially useful for:

  • Closing files
  • Releasing database connections
  • Cleaning temporary resources

Catching All Exceptions

Sometimes you may want to catch any unexpected exception.

try:
    value = int("abc")

except Exception as e:
    print("An error occurred:", e)

The exception object e contains detailed information about the error.


🔍 What This Code Does

  1. try: block

    • This is where you put code that might raise an exception (an error).
    • In this case, 10 / 0 is a division by zero, which is not allowed in Python and will raise a ZeroDivisionError.
  2. except Exception as e: block

    • This catches any exception that occurs in the try block.
    • Exception is the base class for most built-in exceptions, so it will catch almost any error.
    • as e stores the error object in the variable e.
  3. print(f"An error occurred: {e}")

    • This prints the error message to the console.
    • For 10 / 0, the output will be:
      An error occurred: division by zero

Comments