Skip to content
Exercises · Q6

Q.Explain catching exceptions using try and except block.

Rajasthan RbseTextbookSubjective· 3mImportance★★★★★
67% · 6/9 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

The try–except block in Python catches and handles runtime errors gracefully, preventing program crashes by separating error-prone code from recovery logic.

Why exception handling exists

When a program encounters an error during execution — dividing by zero, opening a missing file, converting invalid input to an integer — Python raises an exception and, by default, halts the program with a traceback. That abrupt termination is unacceptable in production software: a single bad user input should not crash an entire application.

Exception handling lets you anticipate where errors might occur, catch them when they do, and respond intelligently — log the problem, prompt the user again, use a fallback value — without stopping the program. The try–except construct is Python's mechanism for this separation of concerns: risky operations go in the try block, and recovery code goes in the except block.

The basic try–except structure

try:
    # Code that might raise an exception
    risky_operation()
except ExceptionType:
    # Code that runs if ExceptionType is raised
    handle_error()

How it works:

  1. Python executes the statements inside the try block line by line.
  2. If no exception occurs, the except block is skipped entirely and execution continues after it.
  3. If an exception is raised and its type matches ExceptionType (or is a subclass of it), control immediately jumps to the except block; the rest of the try block is abandoned.
  4. If the exception type does not match, it propagates upward (the program still crashes unless caught elsewhere).

A concrete example: safe division

numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))

try:
    result = numerator / denominator
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

Sample run (error case):

Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.

Sample run (success case):

Enter numerator: 10
Enter denominator: 2
Result: 5.0

Without the try–except, entering 0 as the denominator would crash the program with:

ZeroDivisionError: division by zero

With it, the program catches the exception, prints a friendly message, and continues (or exits gracefully).

Catching multiple exception types

You can handle different errors differently by chaining except clauses:

try:
    age = int(input("Enter your age: "))
    result = 100 / age
    print(f"100 divided by your age is {result}")
except ValueError:
    print("Error: Please enter a valid integer.")
except ZeroDivisionError:
    print("Error: Age cannot be zero.")

Python checks each except clause in order and executes the first one that matches. If the user types "twenty", a ValueError is raised (invalid literal for int()); if they type 0, a ZeroDivisionError is raised during division.

You can also catch multiple exceptions in a single clause using a tuple:

except (ValueError, ZeroDivisionError) as e:
    print(f"Input error: {e}")

The as e syntax binds the exception object to the variable e, letting you inspect its message or type.

The generic except clause

An except without a type catches any exception:

try:
    risky_code()
except:
    print("Something went wrong.")
Watch out

Bare except: is dangerous in practice. It catches everything, including KeyboardInterrupt (Ctrl+C) and SystemExit, making your program impossible to stop cleanly. It also hides bugs you should fix. Use it only for top-level logging in production, and prefer except Exception: (which excludes system-exiting exceptions) if you must catch broadly.

The else and finally clauses

Python's exception handling supports two optional clauses:

  • else: runs if the try block completes without raising an exception. Use it for code that should run only on success but doesn't belong in the try block itself (because you don't want to catch its exceptions).

    try:
        f = open("data.txt", "r")
    except FileNotFoundError:
        print("File not found.")
    else:
        content = f.read()
        print(content)
        f.close()
    
  • finally: runs always, whether an exception occurred or not, even if the try or except block contains a return or break. Use it for cleanup — closing files, releasing locks, committing or rolling back transactions.

    try: …
    

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.