Python

Exception Handling in Python is a mechanism used to handle runtime errors, ensuring that the program's flow is not interrupted even when an unexpected event occurs. It allows you to "catch" errors and handle them gracefully rather than letting the program crash.

1. Theoretical Overview

What is an Exception?

An Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. While Syntax Errors (like missing a colon) prevent code from running at all, Exceptions occur when syntactically correct code encounters an error during execution (e.g., trying to open a file that doesn't exist).

The try-except Block

The core of exception handling involves four keywords:

  1. try: This block contains the code that might throw an error.

  2. except: This block contains the code that executes if an error occurs in the try block.

  3. else: (Optional) Code here runs only if no exceptions were raised in the try block.

  4. finally: (Optional) Code here runs no matter what, regardless of whether an exception occurred. This is perfect for closing files or database connections.

Common Python Exceptions

  • FileNotFoundError: Raised when a file or directory is requested but doesn't exist.

  • ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.

  • ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.

  • TypeError: Raised when an operation is applied to an object of an inappropriate type.

2. Code Implementation

A. Basic Exception Handling

This example prevents a crash when a user tries to divide by zero or enters non-numeric data.

Python
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: You cannot divide by zero!")
except ValueError:
    print("Error: Please enter a valid integer.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
else:
    print(f"Success! The result is {result}")
finally:
    print("Execution complete.")

B. Exception Handling in File Operations

This is a standard practice to ensure files are handled safely.

Python
try:
    with open("config_data.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("Error: The file 'config_data.txt' was not found.")
except PermissionError:
    print("Error: You do not have permission to read this file.")

C. Raising Custom Exceptions

You can manually trigger an exception using the raise keyword if a specific condition is met.

Python
def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return f"Age is {age}"

try:
    print(check_age(-5))
except ValueError as error:
    print(error)

3. Why Use Exception Handling?

BenefitDescription
RobustnessPrevents the application from crashing in front of the user.
Clean CodeSeparates error-handling logic from the main functional code.
DebuggingProvides specific error messages that help developers find issues faster.
Resource SafetyEnsures files and network connections are closed using the finally block.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now