</> Code Editor

Python Exception Handling (try-except) Exercises


1/15

Python Exception Handling (try-except) Practice Questions

Correct
0%

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:

  1. Execution enters the try block and runs statements sequentially.
  2. 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.
  3. 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.
  4. 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.

Quick Recap of Python Exception Handling (try-except) Concepts

If you are not clear on the concepts of Exception Handling (try-except), you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.

What Is Exception Handling?

In Python, an exception is an event that disrupts the normal flow of the program. Exception handling provides a mechanism to catch these events and respond appropriately. Instead of terminating abruptly, Python can execute alternative code or display meaningful error messages.

The core syntax involves the try and except blocks:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

try block: The code that might raise an exception is placed here.
except block: Handles the specific error if it occurs.

Common Exceptions in Python

Python provides a variety of built-in exceptions that handle different runtime errors. Understanding common exceptions helps write robust code.

Exception Description Example
ZeroDivisionError Occurs when dividing by zero.
10 / 0
FileNotFoundError Occurs when a file does not exist.
open("data.txt")
ValueError Raised when a function receives an argument of the right type but inappropriate value.
int("abc")
TypeError Occurs when an operation is applied to an object of inappropriate type.
"5" + 5
IndexError Raised when trying to access an index that is out of range.
lst[10]
KeyError Occurs when a dictionary key is not found.
dict["name"]

Multiple Except Blocks in Python Exception Handling

Python allows multiple except blocks to handle different types of exceptions separately. This makes it possible to respond appropriately depending on the type of error encountered.


try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
    

Using multiple except blocks allows specific error messages or corrective actions for different exception types instead of handling all errors the same way.

The else and finally Blocks

Python provides else and finally blocks to further control exception handling:

  • else: Executes only if no exception occurs in the try block.
  • finally: Executes regardless of whether an exception occurred. Useful for cleanup actions like closing files or releasing resources.

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
else:
    print("File read successfully.")
finally:
    print("Execution completed.")
    

Using else and finally makes your exception handling more structured, readable, and safe for resource management.

Why Use Exception Handling in Python?

Exception handling in Python is essential for building robust and user-friendly applications. It provides several benefits:

  • Prevents program crashes and improves user experience.
  • Makes code more robust and easier to maintain.
  • Provides a clear mechanism for handling errors, especially in large applications.
  • Allows safe resource management, such as closing files or releasing network connections.

By anticipating potential errors, you can control program flow and respond appropriately instead of letting unexpected exceptions terminate your application.

Best Practices for Exception Handling in Python

To ensure your exception-handling code is safe, readable, and maintainable, follow these guidelines:

  • Catch specific exceptions rather than using a bare except:.
  • Use finally or context managers (with) to ensure resources are properly released.
  • Avoid hiding exceptions; always log or report errors for debugging.
  • Keep try blocks minimal—only include code that might raise the exception.
  • Use meaningful error messages to help users or developers understand the problem.

Following these best practices ensures your Python programs handle errors gracefully, remain reliable, and are easier to debug and maintain.



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.