Exception Handling in Python

In Python, errors can occur during program execution, known as exceptions. If not handled properly, these exceptions can terminate your program. Exception handling allows developers to anticipate and manage these errors gracefully without crashing the application.

What is an Exception?

An exception is an event that disrupts the normal flow of a program. Common examples include:

ZeroDivisionError: Division by zero
ValueError: Invalid value provided to a function
FileNotFoundError: Trying to open a file that doesn't exist

Example:

a = 10
b = 0
print(a / b)   # ZeroDivisionError: division by zero

The try-except Block

Python provides the try-except block to handle exceptions.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input!")
The code inside try runs first. If an exception occurs, the control moves to the matching except block.

Using else and finally

You can also use else and finally with try-except to handle logic more precisely.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Result:", result)
finally:
    print("Execution completed.")
else โ†’ Runs only if no exception occurs.
finally โ†’ Always executes, even if an error occurs โ€” often used for cleanup (like closing files or releasing resources).

Raising Exceptions Manually

You can manually raise exceptions using the raise keyword.

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

Creating Custom Exceptions

Sometimes, you need your own error types to represent application-specific issues. You can create a custom exception by extending the built-in Exception class.

class AgeTooLowError(Exception):
    """Custom exception for invalid age"""
    pass

def check_age(age):
    if age < 18:
        raise AgeTooLowError("Age must be at least 18.")
    else:
        print("Valid age.")

try:
    check_age(15)
except AgeTooLowError as e:
    print("Custom Exception:", e)

Handling Multiple Exceptions

You can handle multiple exceptions together:

try:
    x = int(input("Enter number: "))
    print(10 / x)
except (ZeroDivisionError, ValueError) as e:
    print("Error occurred:", e)
This keeps your code concise and efficient.

Summary

Exception handling is a key part of writing robust, user-friendly programs. By using try, except, else, and finally, you can make your applications fault-tolerant and professional.

Concept Description
try Code block to test for errors
except Handles exceptions that occur in try
else Executes only if no exception occurs
finally Executes regardless of whether an exception occurs
raise Manually trigger an exception
Custom Exception User-defined exception for specific errors
Custom exceptions further enhance clarity and control, making your code more expressive and maintainable. In the next article, we'll explore File Handling in Python โ€” reading, writing, and managing files efficiently.
Share this Article