What happens if an exception occurs inside the try block and there is no corresponding except block to handle it?
# Example: exception without except
try:
x = 10 / 0
print("This line is never reached if exception is not handled")
Uncaught exceptions and program termination
Option 1 – Incorrect: Python does not silently ignore uncaught exceptions; the error is not ignored.
Option 2 – Correct: If an exception occurs in a try block and there is no matching except, Python raises the exception, prints a traceback, and the program stops (unless the exception is caught further up the call stack).
Option 3 – Incorrect: A finally block (if present) will run, but after that Python still propagates the uncaught exception — the program does not exit silently.
Option 4 – Incorrect: Exceptions are not automatically logged and suppressed; they cause a traceback by default unless explicitly handled.
Step-by-step reasoning:
Execution enters the try block and runs statements sequentially.
If a statement raises an exception and there is no except clause matching that exception type, Python searches up the call stack for a handler.
If no handler is found anywhere, Python prints a traceback showing the exception type and location, and the program terminates with a non-zero exit status.
If a finally block exists, it executes before termination, but it does not suppress the uncaught exception.
Key takeaways:
Always handle expected exceptions with appropriate except clauses to avoid program crashes.
finally is useful for cleanup (e.g., closing files) but does not replace exception handling.
For unexpected errors, consider catching generic exceptions at a top level to log and exit gracefully, but prefer catching specific exceptions where possible.
What will happen when you run the following Python code?
try:
value = int("abc")
except ValueError:
print("Invalid conversion!")
# Example demonstrating ValueError handling
try:
value = int("abc")
except ValueError:
print("Invalid conversion!")
Understanding how try-except works:
In the try block, Python attempts to execute int("abc").
This operation raises a ValueError because the string "abc" is not a valid integer representation.
The raised ValueError is immediately caught by the except ValueError: block.
The statement inside except executes — in this case, it prints "Invalid conversion!".
Why the other options are incorrect:
Option 1: Incorrect — The program does not crash because the exception is properly caught.
Option 2: Incorrect — The code never prints the string "abc".
Option 4: Incorrect — Python does not ignore exceptions silently; if unhandled, they raise errors, but here it’s handled.
Step-by-step reasoning:
Interpreter enters the try block.
int("abc") triggers a ValueError.
Control jumps immediately to the except ValueError block.
The message "Invalid conversion!" is printed.
Output:
Invalid conversion!
Key takeaway: Use try-except to handle predictable errors like invalid user input or failed conversions, ensuring that your program continues running smoothly instead of crashing.
In Python, what happens when no except block matches the exception raised inside a try block?
Explanation:
When an exception occurs inside a try block, Python looks for an except block that matches the type of the raised exception. If no matching except block is found:
The exception is not handled locally.
Python stops executing the current function or script.
An error traceback message is printed to the console.
Since no matching except is found, Python raises an unhandled ZeroDivisionError.
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(10 / 0)
ZeroDivisionError: division by zero
Key takeaway: If no except block matches the raised exception, Python will stop execution and display an error traceback. To prevent this, always include the correct exception type or a generic except Exception: to handle unexpected errors safely.
What will be printed by the following code snippet?
Let’s break down how the try-except-else-finally flow works in this example:
int("abc") raises a ValueError because "abc" cannot be converted to an integer.
The except ValueError block runs and prints "Conversion failed!".
The else block is skipped since an exception occurred.
The finally block always runs, printing "Program completed.".
Output:
Conversion failed!
Program completed.
Key takeaway:
The finally block executes whether an exception occurs or not.
else only runs if no exception occurs inside the try block.
Which of the following statements about Python’s exception handling is true?
Explanation:
In Python, you can handle different exceptions separately by using multiple except blocks. This allows more precise control over how various errors are handled.
Example:
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid number entered.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print("Result:", result)
finally:
print("Operation finished.")
Explanation of options:
Option 1 – Incorrect:else runs only when no exception occurs.
Option 2 – Incorrect:finally executes whether or not an exception occurs.
Option 3 – Correct: You can use multiple except blocks for different exceptions.
Option 4 – Incorrect:try can contain return statements.
Key takeaways:
Multiple except clauses improve error-specific handling.
else executes only when no exceptions occur.
finally always runs — even if there’s a return statement or exception.
What will be the output of the following code snippet?
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Division by zero!"
else:
return f"Result is {result}"
finally:
print("Execution completed.")
print(divide_numbers(10, 2))
print(divide_numbers(5, 0))
Explanation:
This example demonstrates how try-except-else-finally interacts with return statements:
Call divide_numbers(10, 2):
a / b → 10 / 2 = 5.0 → no exception.
else block executes → returns "Result is 5.0".
finally always executes → prints "Execution completed."
Call divide_numbers(5, 0):
5 / 0 raises ZeroDivisionError.
except block executes → returns "Division by zero!"
finally executes → prints "Execution completed."
Output:
Execution completed.
Result is 5.0
Execution completed.
Division by zero!
Key takeaways:
finally executes before the value is returned from try, except, or else.
Use finally for cleanup actions like logging, closing files, or releasing resources.
Return values are not affected by finally unless finally contains a return itself.
You are reading a file that may not exist. Which of the following code snippets safely handles the situation and ensures the file is closed properly?
Explanation:
This example demonstrates the safest way to read a file while handling exceptions:
Option 1 – Incorrect: Opens the file without handling exceptions; will crash if the file does not exist.
Option 2 – Incorrect: Catches FileNotFoundError, but if the file opens successfully, f is never closed if another error occurs.
Option 3 – Incorrect: Uses finally to close, but f.close() will raise NameError if the file was not successfully opened.
Option 4 – Correct: Using with automatically handles file opening and closing, and raises exceptions if the file does not exist. The resource is properly released even if an exception occurs.
Step-by-step reasoning:
with open("data.txt") as f: opens the file and assigns it to f.
Reading with f.read() works if the file exists.
When the block exits (even if an exception occurs), the file is automatically closed.
If the file does not exist, a FileNotFoundError is raised and can be caught externally if needed.
Key takeaways:
Always prefer with statement for file operations — ensures proper resource management.
try-except-finally is useful for more complex resource handling but can be error-prone if the resource isn’t successfully initialized.
Which of the following code snippets correctly handles a division by zero and logs a message without stopping the program?
Explanation:
This example demonstrates proper exception handling for a runtime error:
Option 1 – Incorrect: No exception handling; program will crash with ZeroDivisionError.
Option 2 – Incorrect: Catches generic Exception, which works, but the message is less specific; finally not used for cleanup/logging.
Option 3 – Correct: Specifically catches ZeroDivisionError and prints an informative message. The finally block always executes, logging that the operation finished.
Option 4 – Incorrect: Only finally is used; the exception is not caught, so the program still crashes after printing.
Step-by-step reasoning:
try block executes result = 10 / 0, which raises ZeroDivisionError.
except ZeroDivisionError block runs → prints "Cannot divide by zero".
finally block executes → prints "Operation finished".
The program continues execution safely without crashing.
Output:
Cannot divide by zero
Operation finished
Key takeaways:
Use specific exception types to provide meaningful error handling.
The finally block is ideal for cleanup or logging regardless of whether an exception occurs.
A well-structured try-except-finally ensures program stability even in error scenarios.
What will be the output of the following code snippet?
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Division by zero!"
else:
return f"Result is {result}"
finally:
print("Execution finished.")
print(divide(10, 2))
print(divide(5, 0))
Explanation:
This example demonstrates how try-except-else-finally interacts with return statements in Python:
Call divide(10, 2):
No exception occurs → else block executes → returns "Result is 5.0".
finally block executes first → prints "Execution finished".
Then the returned value "Result is 5.0" is passed to the caller.
The return value "Division by zero!" is passed to the caller.
Output:
Execution finished.
Result is 5.0
Execution finished.
Division by zero!
Key takeaways:
finally always executes before returning a value from try or except.
Return values are preserved after finally execution.
This pattern ensures that cleanup, logging, or other final actions are performed consistently.
Which of the following statements about Python’s exception handling is true?
Explanation:
Python’s exception handling allows flexibility to manage errors efficiently. Here’s how the blocks work:
Option 1 – Incorrect: The finally block always executes, regardless of whether an exception occurs.
Option 2 – Incorrect: The else block executes only if no exception occurs in the try block.
Option 3 – Incorrect: A try block can have multiple except clauses for different exception types.
Option 4 – Correct: Multiple except blocks can be used to handle specific exception types differently, improving clarity and error management.
Example:
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid number entered.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print("Result is", result)
finally:
print("Execution completed.")
Key takeaways:
Use multiple except blocks to handle different exceptions explicitly.
The else block is optional and runs only if the try block succeeds.
The finally block is ideal for cleanup actions like closing files or releasing resources.
What will be the output of the following code snippet?
def process_list(numbers):
result = []
for n in numbers:
try:
result.append(10 / n)
except ZeroDivisionError:
result.append(None)
finally:
print(f"Processed {n}")
return result
nums = [5, 0, 2]
print(process_list(nums))
Explanation:
This example demonstrates try-except-finally inside a loop for handling exceptions on multiple inputs:
Always catch the correct exception type for the operation.
Gracefully handle errors to avoid program crashes.
Appending a sentinel value like "Error" or None allows continued processing.
You want to read integers from a file and safely handle possible errors. Which of the following code snippets ensures that the file is properly closed even if an exception occurs?
Explanation:
This question tests safe file handling with exception handling:
Option 1 – Incorrect: f.close() is called outside a try → if an exception occurs during reading or conversion, the file may not close.
Option 2 – Incorrect: Ensures finally closes the file, but lacks exception-specific handling (e.g., ValueError), so errors may still stop the program.
Option 3 – Incorrect: Catches ValueError, but if another exception occurs (like FileNotFoundError), the file may remain open.
Option 4 – Correct: Using with ensures the file is automatically closed, even if exceptions occur. Also handles all exceptions safely.
Step-by-step reasoning:
with open("numbers.txt") as f: → context manager opens the file and guarantees closure.
Read the file → data = f.read().
Convert each item to integer safely → numbers = [int(x) for x in data.split()].
File automatically closed when block ends.
Key takeaways:
Use with statement for safe and concise file handling.
finally can be used, but context managers are cleaner and less error-prone.
Always handle potential exceptions when reading and converting data from files.
Consider the following code snippet. What will be printed?
def test_nested(n):
try:
if n == 0:
raise ValueError("Zero not allowed")
try:
print(10 // n)
except ZeroDivisionError:
print("Inner ZeroDivisionError")
except ValueError as ve:
print("Outer:", ve)
finally:
print("Finally block executed")
test_nested(0)
Explanation:
This code demonstrates nested try-except and the interaction of finally:
Option 1 – Correct: The outer except catches the ValueError → prints "Outer: Zero not allowed". The finally block always executes → prints "Finally block executed".
Option 2 – Incorrect: ZeroDivisionError never occurs because n = 0 raises ValueError before the inner try executes.
Option 3 – Incorrect: Misses finally output.
Option 4 – Incorrect: Order of finally and outer except is wrong.
Step-by-step reasoning:
n = 0 → if n == 0: raise ValueError triggers.
Inner try never executes because exception is raised before it.
Outer except ValueError prints the message.
finally block executes afterward.
Key takeaways:
Exceptions raised before a try block prevent inner code from running.
finally always executes after the outer try-except, even if an exception is caught.
Check What You’ve Learned
Practicing Python Exception Handling (try-except)? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Exception Handling (try-except)
Every Python developer faces errors at some point, but what separates a beginner from a skilled programmer is how effectively they handle those errors. At Solviyo, we’ve designed a detailed collection of Python exception handling exercises with explanations and answers to help you understand how to write programs that don’t just crash — but recover gracefully using try-except blocks.
In these exercises, we start with the basics of exception handling in Python. You’ll learn what exceptions are, why they occur, and how the try and except statements work together to manage runtime errors. Through practical examples and clear explanations, we show how to anticipate errors like division by zero, file not found, or invalid input, and handle them smoothly. Each exercise is built to help you think like a Python developer — identifying potential problem areas before they break your program.
As you move ahead, we go deeper into more advanced aspects of exception handling. You’ll explore using else and finally blocks, catching multiple exceptions, and even raising custom exceptions using raise. Each concept is supported by Python exercises, MCQs, and detailed answers so you can immediately test your understanding and clear any confusion. The focus isn’t just on writing correct syntax but on developing logical thinking and clean error-handling strategies.
Our exercises mirror real-world Python applications where handling exceptions is a must. From file operations and user input validation to network requests and API responses, you’ll learn how to make your code reliable and user-friendly. Each problem is followed by a step-by-step explanation and answer to help you understand not just what works — but why it works.
We also include short Python MCQs with answers for quick practice and self-assessment. These help reinforce your grasp of key topics like exception hierarchy, multiple exception handling, and the role of finally in resource cleanup. Whether you’re preparing for coding interviews, assignments, or professional projects, these MCQs make it easier to recall important exception-handling techniques quickly.
At Solviyo, we believe that good programming isn’t just about solving problems — it’s about preventing them. That’s exactly what Python’s exception handling empowers you to do. By completing these exercises with explanations and answers, you’ll gain a strong command over error handling and be able to write programs that are both robust and elegant. Start practicing now and make Python’s try-except your best debugging partner.