Python Error Handling

Error handling in Python is done with try, except, else, and finally statements. This structure allows you to gracefully handle errors and perform cleanup operations if needed.

Basic Error Handling


try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

try: Block of code that might raise an exception.

except: Code to execute if an exception occurs. You can specify specific error types like ZeroDivisionError or use a general exception handler.

Catching Multiple Exceptions

You can catch multiple specific exceptions by listing them in a tuple or by using multiple except blocks.


try:
    result = int("abc")
except (ValueError, TypeError) as e:
    print(f"Error occurred: {e}")

Or:


try:
    result = int("abc")
except ValueError:
    print("Error: Cannot convert string to integer.")
except TypeError:
    print("Error: Invalid type used.")

Using a General Exception

To catch any exception, use except Exception or simply except. This can be helpful for logging or debugging, but it’s usually good to handle specific errors where possible.


try:
    result = 10 / 0
except Exception as e:
    print(f"An unexpected error occurred: {e}")

else Clause

The else block runs if no exceptions were raised in the try block.


try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error: Division by zero.")
else:
    print("No errors occurred. Result is:", result)

finally Clause

The finally block runs no matter what, whether an exception occurred or not. It’s often used for cleanup actions (e.g., closing files or database connections).


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

Raising Exceptions

You can use raise to throw an exception if a condition isn’t met.


def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b

try:
    print(divide(10, 0))
except ValueError as e:
    print(e)

Custom Exception Classes

You can create custom exceptions by subclassing Python’s built-in Exception class.


class CustomError(Exception):
    pass

def risky_function():
    raise CustomError("This is a custom error.")

try:
    risky_function()
except CustomError as e:
    print(e)

Python Error Handling – Interview Questions

Q 1: What is error handling in Python?
Ans: It manages runtime errors using try, except, and finally.
Q 2: What is the difference between syntax errors and exceptions?
Ans: Syntax errors occur at compile-time, exceptions at runtime.
Q 3: Can multiple exceptions be handled in one block?
Ans: Yes, by specifying a tuple of exception types.
Q 4: What is the use of the finally block?
Ans: To execute code regardless of whether an exception occurred.
Q 5: How do you raise an exception manually?
Ans: Using the raise keyword.

Python Error Handling – Objective Questions (MCQs)

Q1. Which statement is used in Python to handle exceptions?






Q2. What will happen if an exception occurs in the try block and no except block is provided?






Q3. What is the correct syntax to handle multiple exceptions in Python?






Q4. Which block is always executed, whether an exception occurs or not?






Q5. What is the purpose of the raise statement in Python?






Related Python Error Handling Topics