Python Exception Handling Questions
Introduction
Exception handling is a crucial part of writing robust Python programs. It allows your code to respond gracefully to unexpected errors.
This tutorial covers common questions about Python exception handling, practical examples, and tips to prepare for technical interviews.
Errors should never pass silently.
What is Exception Handling in Python?
Exception handling in Python is a mechanism to catch and manage errors that occur during program execution.
Instead of crashing, the program can handle exceptions and continue or exit gracefully.
- Uses try, except, else, and finally blocks.
- Catches specific or general exceptions.
- Improves program reliability and user experience.
Common Exception Handling Questions
Below are frequently asked questions about Python exception handling, useful for interviews and practical coding.
How do you catch multiple exceptions?
You can catch multiple exceptions by specifying them as a tuple in a single except block.
- Example: except (TypeError, ValueError):
- This handles both TypeError and ValueError exceptions.
What is the purpose of the else block in try-except?
The else block runs if no exceptions are raised in the try block.
It is useful for code that should only execute when the try block succeeds.
- Helps separate error handling from normal code execution.
When should you use finally?
The finally block executes regardless of whether an exception occurred or not.
It is typically used for cleanup actions like closing files or releasing resources.
- Ensures important cleanup code always runs.
How do you raise exceptions manually?
You can raise exceptions using the raise keyword followed by an exception instance or class.
- Example: raise ValueError('Invalid input')
- Useful for enforcing constraints or signaling errors.
What is the difference between Exception and BaseException?
BaseException is the root of all exceptions, including system-exiting exceptions.
Exception is the base class for most user-defined and built-in exceptions.
- Avoid catching BaseException unless you intend to catch system exit signals.
- Catching Exception is safer for general error handling.
Practical Examples
Let's look at some code examples demonstrating Python exception handling concepts.
Catching Multiple Exceptions
This example catches both ValueError and ZeroDivisionError exceptions.
Using else and finally
This example shows how else and finally blocks work with try-except.
Examples
try:
x = int(input('Enter a number: '))
y = 10 / x
except (ValueError, ZeroDivisionError) as e:
print(f'Error occurred: {e}')
else:
print(f'Result is {y}')
finally:
print('Execution complete.')This code handles invalid input and division by zero, prints the result if no error, and always prints completion message.
def check_age(age):
if age < 0:
raise ValueError('Age cannot be negative')
print(f'Age is {age}')
try:
check_age(-5)
except ValueError as e:
print(f'Caught error: {e}')This example raises a ValueError if the age is negative and catches it in the calling code.
Best Practices
- Catch specific exceptions instead of a general Exception to avoid masking bugs.
- Use finally blocks to release resources like files or network connections.
- Avoid using bare except clauses without specifying exception types.
- Raise exceptions with clear, descriptive messages.
- Use else blocks to separate normal execution code from error handling.
Common Mistakes
- Catching all exceptions with a bare except, hiding unexpected errors.
- Not using finally to clean up resources, causing resource leaks.
- Raising exceptions without informative messages.
- Ignoring exceptions silently without logging or handling.
- Using exceptions for normal control flow instead of actual errors.
Hands-on Exercise
Implement Exception Handling for File Reading
Write a Python function that reads a file and handles exceptions if the file does not exist or cannot be read.
Expected output: The function should print an error message if the file is missing or unreadable, otherwise print the file contents.
Hint: Use try-except to catch FileNotFoundError and IOError exceptions.
Raise Custom Exception
Create a custom exception class and raise it when a function receives invalid input.
Expected output: The program should catch and display the custom exception message.
Hint: Define a new exception class inheriting from Exception and use raise to trigger it.
Interview Questions
How do you handle multiple exceptions in a single except block?
InterviewYou can catch multiple exceptions by specifying them as a tuple in the except clause, e.g., except (TypeError, ValueError):
What is the difference between else and finally in try-except?
InterviewThe else block runs only if no exceptions occur, while finally always runs regardless of exceptions, typically for cleanup.
Why should you avoid catching BaseException?
InterviewBecause BaseException includes system-exiting exceptions like KeyboardInterrupt and SystemExit, catching it can interfere with program termination.
Summary
Python exception handling is essential for writing reliable and maintainable code.
Understanding try, except, else, and finally blocks helps you manage errors effectively.
Practice catching specific exceptions and raising meaningful errors to improve your programs.
This knowledge is also valuable for technical interviews and real-world development.
FAQ
Can you catch multiple exceptions in one except block?
Yes, by specifying a tuple of exception types in the except clause, you can handle multiple exceptions together.
What happens if an exception is not caught?
If an exception is not caught, it propagates up the call stack and may terminate the program with a traceback.
Is it good practice to use a bare except clause?
No, bare except clauses catch all exceptions including system-exiting ones and can hide bugs. It's better to catch specific exceptions.
