Python Interview Questions

32 Questions
Python

Python

Web DevelopmentFrontendBackendData Science

Question 12

How do you handle exceptions in Python?

Answer:

In Python, exceptions are handled using the try, except, else, and finally blocks. These constructs allow you to catch and manage errors that occur during the execution of your code, ensuring that your program can gracefully handle unexpected situations.

Basic Exception Handling with try and except

The most basic form of exception handling involves the try and except blocks. The try block contains the code that might raise an exception, while the except block contains the code that executes if an exception occurs.

try:
    # Code that might raise an exception
    x = 10 / 0
except ZeroDivisionError:
    # Code to handle the exception
    print("Cannot divide by zero")

Handling Multiple Exceptions

You can handle multiple exceptions by specifying multiple except blocks. Each except block can handle a different type of exception.

try:
    # Code that might raise an exception
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input. Please enter a valid number")

Using else Block

The else block can be used to execute code if no exceptions are raised in the try block.

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input. Please enter a valid number")
else:
    print("The result is", result)

Using finally Block

The finally block can be used to execute code regardless of whether an exception was raised or not. This is often used for cleanup actions.

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input. Please enter a valid number")
else:
    print("The result is", result)
finally:
    print("This will always execute")

Catching All Exceptions

To catch any type of exception, you can use a bare except clause. However, this is generally discouraged because it can make debugging more difficult and catch exceptions you didn't intend to handle.

try:
    # Code that might raise an exception
    x = 10 / 0
except:
    # Code to handle any exception
    print("An error occurred")

Accessing Exception Information

You can access information about the exception using the as keyword.

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Exception occurred:", e)

Raising Exceptions

You can raise exceptions using the raise keyword.

def check_value(value):
    if value < 0:
        raise ValueError("Value cannot be negative")
    return value

try:
    check_value(-1)
except ValueError as e:
    print("Exception occurred:", e)

Custom Exceptions

You can define your own exceptions by creating a class that inherits from the Exception class.

class CustomError(Exception):
    pass

try:
    raise CustomError("This is a custom error")
except CustomError as e:
    print("Exception occurred:", e)

Summary

Handling exceptions in Python involves using try, except, else, and finally blocks to manage and respond to errors that occur during program execution. By properly handling exceptions, you can make your programs more robust and user-friendly.

Recent job openings