Exception Handling (Try, Except)

1. Introduction

Exception handling in Python helps manage errors gracefully without crashing the program. It uses the try, except, else, and finally blocks to catch and handle exceptions.


2. Understanding Exceptions

An exception is an error that occurs during execution, stopping the program.

Common Exceptions in Python

ExceptionCause
ZeroDivisionErrorDivision by zero (5 / 0)
TypeErrorInvalid type operation ("5" + 5)
ValueErrorIncorrect value format (int("abc"))
FileNotFoundErrorTrying to open a non-existent file
IndexErrorAccessing an invalid index in a list
KeyErrorAccessing a non-existent key in a dictionary

3. Using Try and Except

The try block runs the code, and if an error occurs, the except block executes.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except ValueError:
    print("Error: Invalid input! Please enter a number.")

If the user enters 0, ZeroDivisionError is handled.
If the user enters "abc", ValueError is handled.


4. Catching Multiple Exceptions

You can handle multiple exceptions in a single except block.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except (ZeroDivisionError, ValueError) as e:
    print("An error occurred:", e)

as e stores the actual error message.


5. Using Else with Try-Except

The else block runs if no exception occurs.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input!")
else:
    print("Successful! The result is:", result)

If no exception occurs, the else block runs.
If an error occurs, the else block is skipped.


6. Finally Block

The finally block always executes, whether an exception occurs or not.

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Closing file (if opened).")
    if 'file' in locals():
        file.close()

The finally block is useful for cleanup operations like closing files or releasing resources.


7. Raising Exceptions Manually

You can raise exceptions using raise.

age = int(input("Enter your age: "))
if age < 18:
    raise ValueError("You must be at least 18 years old.")

This manually triggers a ValueError if the user enters an age below 18.


8. Summary

Use try to test code that might cause an error.
Use except to handle specific errors.
Use else to execute code when no exception occurs.
Use finally to execute cleanup operations.
Use raise to manually trigger exceptions.