LearnFrenzy
Sign in Take a free test

Python Programming · Topic 16 of 25

Exception Handling Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Exception Handling · Study material

Programs meet bad input, missing files, network failures and division by zero. Python reports such problems by raising an exception; if nothing catches it, the program stops with a traceback. Exception handling lets a program react instead: retry, use a default, show a clear message, or clean up before failing. Interviews and written tests ask exactly how try, except, else and finally run, which handler catches what, how to write custom exceptions and why a bare except: is dangerous. This topic covers it all, then 50 practice questions run on Python 3.

On this page

  • Syntax errors vs exceptions
  • try / except, catching several types, except … as e
  • else and finally – the full order of execution
  • The exception hierarchy
  • raise, re-raise, custom exceptions and raise … from
  • EAFP vs LBYL, and the anti-patterns to avoid

Syntax errors versus exceptions

A syntax error (or IndentationError) is found when Python compiles the file, before anything runs, and cannot be caught by the same file. An exception happens while the program runs – ZeroDivisionError, ValueError, KeyError, IndexError, TypeError, FileNotFoundError … – and can be handled.

try and except

Put the code that may fail in a try block. If an exception occurs, Python skips the rest of the block and looks for an except clause that matches the exception's type; except SomeError as e also gives you the exception object, whose str() is the message. If no clause matches, the exception propagates to the caller – and, if nobody handles it, stops the program.

def safe_divide(a, b):
    try:
        return a / b                       # code that may fail
    except ZeroDivisionError:              # runs only if THAT exception happens
        print("Cannot divide by zero")
        return None

print(safe_divide(10, 4))
print(safe_divide(10, 0))

for text in ["42", "4.2", "forty"]:
    try:
        n = int(text)
        print(text, "->", n)
    except ValueError as e:                # 'as e' gives the exception object
        print(text, "->", type(e).__name__, ":", e)

Output

2.5
Cannot divide by zero
None
42 -> 42
4.2 -> ValueError : invalid literal for int() with base 10: '4.2'
forty -> ValueError : invalid literal for int() with base 10: 'forty'

else and finally

The full statement is try → except … → else → finally. else runs only if the try block raised nothing – put the "success" code there so the try block stays small. finally runs always: after success, after a handled exception, after an unhandled one, and even when the try block returns. It is the place for clean-up such as closing files or releasing locks.

def process(value):
    print(f"--- process({value!r})")
    try:
        n = int(value)
        print("  try: converted", n)
    except ValueError:
        print("  except: not a number")
    else:
        print("  else: runs only when try raised nothing")
    finally:
        print("  finally: runs in every case")

process("7")
process("x")

Output

--- process('7')
  try: converted 7
  else: runs only when try raised nothing
  finally: runs in every case
--- process('x')
  except: not a number
  finally: runs in every case

Handling several exception types

Use several except clauses, or one clause with a tuple: except (TypeError, ZeroDivisionError):. Clauses are checked from top to bottom and the first match wins, so put specific exceptions before general ones.

def lookup(data, key):
    try:
        return 100 / data[key]
    except KeyError:
        return f"no key {key!r}"
    except (ZeroDivisionError, TypeError) as e:      # one handler, several types
        return f"bad value ({type(e).__name__})"

stock = {"pen": 4, "ink": 0, "pad": "five"}
for k in ["pen", "ink", "pad", "bag"]:
    print(k, "->", lookup(stock, k))

Output

pen -> 25.0
ink -> bad value (ZeroDivisionError)
pad -> bad value (TypeError)
bag -> no key 'bag'

The exception hierarchy

Exceptions are classes arranged in a tree. BaseException is the root; Exception is the base of all ordinary errors (but not of KeyboardInterrupt and SystemExit). LookupError is the parent of IndexError and KeyError, ArithmeticError of ZeroDivisionError, and OSError of FileNotFoundError and PermissionError. Catching a class also catches all its subclasses.

# Exceptions are classes; except catches the class AND its subclasses
print(ZeroDivisionError.__mro__[1].__name__)      # ArithmeticError
print(issubclass(KeyError, LookupError), issubclass(IndexError, LookupError))
print(issubclass(ValueError, Exception), issubclass(KeyboardInterrupt, Exception))

for action in [lambda: [1, 2][5], lambda: {"a": 1}["b"]]:
    try:
        action()
    except LookupError as e:                      # catches both IndexError and KeyError
        print("LookupError caught:", type(e).__name__)

Output

ArithmeticError
True True
True False
LookupError caught: IndexError
LookupError caught: KeyError

raise and custom exceptions

raise ValueError("message") signals an error from your own code. For errors specific to your program, define a class that inherits from Exception (or a more specific built-in); it can carry extra data as attributes. Callers can then catch exactly that error.

class InsufficientFundsError(Exception):
    """Raised when a withdrawal is larger than the balance."""
    def __init__(self, balance, amount):
        super().__init__(f"balance {balance}, requested {amount}")
        self.shortfall = amount - balance

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")       # raise a built-in exception
    if amount > balance:
        raise InsufficientFundsError(balance, amount)     # raise your own
    return balance - amount

for amt in [300, -5, 2000]:
    try:
        print("left:", withdraw(1000, amt))
    except InsufficientFundsError as e:
        print("Declined:", e, "| short by", e.shortfall)
    except ValueError as e:
        print("Invalid:", e)

Output

left: 700
Invalid: amount must be positive
Declined: balance 1000, requested 2000 | short by 1000

Re-raising and chaining

A bare raise inside an except block re-raises the current exception – handy for logging and passing it on. raise NewError(...) from e converts a low-level error into one that makes sense at a higher level while keeping the original in __cause__, so the traceback shows both.

def load_port(text):
    try:
        return int(text)
    except ValueError as e:
        # translate a low-level error into a meaningful one, keeping the cause
        raise RuntimeError(f"invalid port setting {text!r}") from e

def log_and_reraise():
    try:
        return 1 / 0
    except ZeroDivisionError:
        print("logged the error")
        raise                                    # re-raise the SAME exception

try:
    load_port("80a")
except RuntimeError as e:
    print(e, "| caused by", type(e.__cause__).__name__)

try:
    log_and_reraise()
except ZeroDivisionError as e:
    print("caught again:", e)

Output

invalid port setting '80a' | caused by ValueError
logged the error
caught again: division by zero

EAFP versus LBYL

Python favours EAFP – try the operation and handle the exception – over LBYL – check every condition first. EAFP avoids race conditions (a file can disappear between a check and the open) and keeps the normal path clean. For simple cases, a method with a default such as dict.get() is clearer than either.

config = {"host": "localhost"}

# LBYL – Look Before You Leap: test first
if "port" in config:
    port = config["port"]
else:
    port = 8080

# EAFP – Easier to Ask Forgiveness than Permission: try, and handle failure (very Pythonic)
try:
    port2 = config["port"]
except KeyError:
    port2 = 8080

print(port, port2, config.get("port", 8080))   # get() is simplest for this case

Output

8080 8080 8080

Common mistakes

  • A bare except: or except Exception: that hides bugs – a typo becomes "invalid input".
  • Broad handlers before specific ones – the specific ones never run.
  • Catching the wrong type – int("x") raises ValueError, not TypeError.
  • Huge try blocks – you cannot tell which line failed, and half-finished work stays done.
  • Using a variable assigned in a failed try – NameError later.
  • raise "message" – only exception objects can be raised.
  • Silently passing – except: pass loses the information you need to fix the problem.

Key points to remember

  • Order: try → matching except → else (if no exception) → finally (always).
  • The first matching except clause wins; specific before general.
  • Catching a class catches its subclasses.
  • raise X("msg") raises; bare raise re-raises; raise X from e chains.
  • Custom exceptions inherit from Exception.
  • Catch only what you can handle; let the rest propagate.
  • The name in except … as e is deleted when the block ends.

Frequently asked questions

What is the difference between an error and an exception?

Informally both describe problems. In Python, syntax errors stop compilation, while exceptions are objects raised at run time that can be caught; most built-in exception classes end in "Error".

Should I use assert for validating user input?

No. assert is for internal checks during development and is removed when Python runs with -O. Validate input with if and raise.

Is it OK to catch Exception?

At the very top of a program (to log and show a friendly message) yes; deep inside code, catch the specific exceptions you expect.

Where can I learn more?

Read Python Exceptions in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links