Explore programming tutorials, exercises, quizzes, and solutions!
Python Exception Handling Exercises
1/20
When writing Python programs, unexpected errors or exceptions may occur, such as dividing by zero, accessing a file that doesn’t exist, or converting invalid data types. To make your programs more robust and user-friendly, Python provides exception handling using the try, except, else, and finally blocks.
Exception handling allows your program to catch and manage errors without crashing, providing a way to respond to issues gracefully, log them, or prompt the user for corrective action.
Consider the following code:
try:
result = 10 / 0
except ZeroDivisionError:
result = None
print(result)
What does this code demonstrate about Python’s exception handling?
This code snippet shows how Python handles exceptions using the try-except structure.
The try block contains code that might raise an error (10 / 0 causes ZeroDivisionError).
The except ZeroDivisionError block catches this specific error and prevents the program from terminating abruptly. Instead, it assigns None to the variable result.
Finally, print(result) outputs None.
Exception handling is essential for building fault-tolerant programs, especially when dealing with user input, file operations, network requests, or any operation prone to failure. By anticipating and managing exceptions, your code can remain stable and provide informative feedback instead of crashing unexpectedly.
Which block executes if an exception occurs in the try block?
The except block handles exceptions that occur in the try block. If no exception is raised, the except block is skipped. The finally block always runs, regardless of an exception.
Which of the following will raise a ZeroDivisionError?
Dividing any number by zero using / raises a ZeroDivisionError. Multiplying by zero or dividing by non-zero values is perfectly valid and does not raise exceptions.
What kind of error does the following code raise?
int("hello")
Trying to convert the string "hello" to an integer fails because it's not a valid numeric string. This raises a ValueError, which indicates an inappropriate value was used for the operation.
Which is the correct syntax to catch all exceptions?
Option1 catches all exceptions derived from the Exception class, which covers almost all standard errors. Option3 is a bare except that catches everything including KeyboardInterrupt and SystemExit. Both are technically correct, but Option1 is preferred for clarity and safety.
What will be the output of the following code?
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Caught:", e)
finally:
print("Always runs")
When 10 / 0 is executed, it raises a ZeroDivisionError, which is caught by the except block. The message "Caught: division by zero" is printed. Then, regardless of the exception, the finally block always runs, printing "Always runs". The finally block is used to release resources or ensure certain code runs no matter what.
Which of the following exceptions is raised by this code?
d = {"name": "Eva"}
print(d["age"])
Accessing a non-existent key in a dictionary raises a KeyError. In this case, the dictionary has a key "name" but not "age". Attempting d["age"] directly will fail, unless .get() is used which returns None instead of raising an error. KeyError helps indicate the exact missing key in traceback.
Calling int("abc") raises a ValueError because the string "abc" cannot be interpreted as an integer. The except block catches this and prints "Cannot convert". Then the finally block is executed, printing "Done". The else block is skipped because an exception occurred.
What will be the output of this code?
try:
a = undefined_variable
except NameError:
print("Variable not defined")
Using a variable that has not been defined raises a NameError. The code catches this using an except NameError block and prints the message "Variable not defined". This is a common runtime error when variables are misspelled or not initialized before use.
What does this code print?
try:
print("Start")
raise Exception("Oops")
except:
print("Caught an exception")
print("After try-except")
The code prints "Start" first. Then raise Exception("Oops") throws a general exception, which is caught by the bare except: block. It prints "Caught an exception". After the exception is handled, control resumes after the except block and prints "After try-except". This shows how exception handling resumes normal flow after recovery.
The inner try block causes a ZeroDivisionError, which is caught and handled by raising a new ValueError. This new exception bubbles up to the outer try-except block, where it is caught and printed. This demonstrates exception chaining and how you can transform one exception into another.
What will be printed?
def divide(x, y):
try:
return x / y
finally:
print("Cleaning up")
divide(4, 2)
The function returns a value, but the finally block is executed just before returning. Since print() returns None, only "Cleaning up" is printed and the actual return value is ignored in the output as it's not being printed in the main code. This shows that finally executes even if the try block has a return statement.
The program prints "A" first, then an exception is raised. The except block catches it and prints "B". Regardless of the error, the finally block runs and prints "C". After all exception handling is done, the normal flow continues and prints "D". This question tests deep understanding of execution order with try-except-finally.
Which option correctly handles multiple exception types?
Python allows catching multiple exceptions by enclosing them in a tuple. The correct syntax is except (TypeError, ValueError):. Using or or comma without parentheses results in syntax errors. This approach is helpful when a block of code could raise different, but related exceptions that can be handled in the same way.
Which of the following ensures that code runs no matter what, even if an error occurs?
The finally block is designed to always execute, regardless of whether an exception occurred or not. It is useful for cleanup actions like closing files or releasing resources. Unlike else or except, which depend on whether exceptions occur, finally is guaranteed to run even if a return or raise is executed in the try block.
The code prints "Start", then raises a ValueError. It's caught and "Caught: Error occurred" is printed. Then the exception is re-raised using raise. Before the exception propagates, the finally block runs, printing "Finally block executed". After that, the unhandled exception causes a traceback. So, the output includes all prints plus a final traceback.
Since 1/0 raises a ZeroDivisionError, the except block handles it, printing "Handled". The else block is skipped because an exception occurred. Then the finally block always runs, printing "Cleanup". This question checks whether you understand when else runs and how finally always executes.
First, "A" is printed. The raise ValueError causes the except block to execute, printing "B". The else block is skipped because an exception occurred. The finally block always executes, printing "D". This tests your understanding of the interaction between all three blocks: try, except, and finally.
What happens when this code runs?
try:
print("Hello")
finally:
print("Goodbye")
This code is valid. The try block executes and prints "Hello". Since there is no except block but a finally block exists, "Goodbye" is printed next. A finally block doesn’t require except or else to be present — it can be used alone with try.
The code attempts to import a non-existent module, which raises a ModuleNotFoundError. Since this is a subclass of ImportError, it would be caught by either block, but Python matches the most specific one first. Therefore, "Module missing" is printed. This demonstrates how Python resolves exception hierarchy when multiple related handlers are defined.
Practicing Python Exception Handling? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Exception Handling
Welcome to the Python Exception Handling exercises — a focused collection designed to help you master the critical skill of managing errors and unexpected situations in your Python programs. Exception handling is essential for writing robust, reliable code that gracefully recovers from runtime issues instead of crashing. Whether you're new to Python or looking to deepen your understanding, these exercises will guide you through the core concepts and best practices.
In this section, you’ll learn how to use try, except, else, and finally blocks effectively to catch and handle different types of exceptions. You’ll practice raising exceptions intentionally using raise, creating custom exception classes, and managing multiple exception types in a clean, organized way.
Understanding exception handling helps you build resilient applications that can deal with invalid input, file I/O errors, network issues, and other unexpected problems without failing abruptly. These exercises emphasize writing clean error-handling code that provides useful feedback to users and logs important information for debugging.
You'll work through practical problems that simulate real-world scenarios — such as handling division by zero, missing files, incorrect data formats, and network timeouts. By mastering these patterns, you’ll gain confidence in anticipating and mitigating potential failures in your code.
Exception handling is a must-have skill for developers working in all domains — from web applications and data processing to automation scripts and system programming. This section also prepares you for technical interviews where error handling questions often test your problem-solving and coding maturity.
Alongside these exercises, we encourage you to explore related Python concepts like logging, assertions, and unit testing to build a comprehensive approach to writing robust, maintainable software. Combining these skills will elevate your coding standards and make your programs more professional.
Start practicing the Python Exception Handling exercises now to develop the expertise needed to write fault-tolerant Python code. With consistent practice, you’ll be ready to handle any error condition gracefully and keep your programs running smoothly.