Exception Handling in Python
Raising Exceptions: raise and assert
Python raises exceptions on its own, and a program can raise one deliberately. The raise statement takes the form raise ExceptionName(optional message) — for example raise ValueError("marks cannot be negative"). As soon as raise executes, the rest of the current block is skipped and Python looks for a handler. The assert statement tests a condition the programmer expects to be true: assert expression, message. If the expression is True nothing happens; if it is False, Python raises AssertionError carrying the message. assert is a quick check on input or on an assumption, such as a number being non-negative before its square root is taken.
For example, this fragment prints 13 and then 4 — the line after raise never runs:try: print("1", end="") raise IndexError print("2", end="")except IndexError: print("3", end="")print("4")
Python raises exceptions on its own, and a program can raise one deliberately. The raise statement takes the form raise ExceptionName(optional message) — for example raise ValueError("marks…
Handling Exceptions: try and except
When an error occurs, Python creates an exception object and hands it to the runtime system — this is called throwing the exception. The runtime system then searches backwards through the calls that led to the error for code that can deal with it, the exception handler; finding one is called catching the exception. If no handler is found anywhere, the program stops. Code that might fail is placed in a try block, and the handler in an except block that names the exception it handles. If the try block runs without an error, every except block is skipped.
- Several except clauses may follow one try, one per exception; Python runs the first whose name matches and skips the rest.
- An except with no exception name catches every exception. It must be the last except clause — placing it earlier is itself a SyntaxError ("default 'except:' must be last").
- An unmatched exception — one no except clause names — is not handled here; it travels outwards to the caller, and if nothing catches it the program terminates.
A worked trace. Each item is tried in turn; "x" cannot become an integer and "0" makes the division fail, so the total is 3 + 100 + 2 + 1000 and the program prints 1105:total = 0for item in ["4", "x", "6", "0"]: try: total += 12 // int(item) except ValueError: total += 100 except ZeroDivisionError: total += 1000print(total)
- Error occurs during execution
- Exception object is thrownHanded to the runtime system
- Runtime searches back for a handlerThrough the calls that led to the error
- Handler found: exception caughtThe first matching except runs
When an error occurs, Python creates an exception object and hands it to the runtime system — this is called throwing the exception. The runtime system then searches backwards through the…
The else and finally Clauses
A try statement can carry two more clauses. The else clause runs only if the try block raised no exception; it is the place for code that should run after the risky part succeeds. The finally clause runs always — whether the try block succeeded, an exception was caught, or an exception was not caught at all — so it is where clean-up goes, such as closing a file. If an exception is not handled, finally still runs first and the exception is then passed on. The order on the page is fixed: try, then the except clauses, then else, then finally.
| What happens in try | except | else | finally |
|---|---|---|---|
| No exception | skipped | runs | runs |
| Exception matched by an except | the matching one runs | skipped | runs |
| Exception matched by none | none runs | skipped | runs, then the exception propagates |
done -1:def f(a, b): try: return a / b except ZeroDivisionError: return -1 finally: print("done", end=" ")print(f(6, 0))(1) which line of try, if any, raises — and was anything printed before it?
(2) which except, if any, matches?
(3) did try finish cleanly, so that else runs? finally is printed last in every case.
A try statement can carry two more clauses. The else clause runs only if the try block raised no exception; it is the place for code that should run after the risky part succeeds. The…
Key takeaways
- Syntax errors are caught while the code is parsed, so nothing runs; exceptions arise during execution of syntactically valid code.
- ValueError: right type, wrong value (int("3.5")); TypeError: wrong type ("5" + 5); IndexError, NameError, ZeroDivisionError, EOFError name their cause.
- raise throws an exception deliberately and skips the rest of the block; assert raises AssertionError when its condition is False.
- Python runs the first matching except; a bare except catches everything and must come last.
- else runs only when try raised nothing; finally runs in every case, even after a return, and before an unhandled exception propagates.
- Throwing creates the exception object; catching is the runtime system finding a handler for it.
Practice questions (25)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
What is the output of the following code?
try:x = int("12a")print("A", end="")except ValueError:print("B", end="")else:print("C", end="")finally:print("D", end="")Show answer
Answer: B — BD
int("12a") raises ValueError on the first line of try, so print("A") never runs; the matching except prints B, else is skipped because try did not finish cleanly, and finally prints D — BD. ABD forgets that the rest of try is abandoned the moment the exception is raised, and BCD runs else, which happens only when try raises nothing.Which exception is raised by the expression int("3.5") in Python 3?
Show answer
Answer: D — ValueError
int() accepts a string argument, so the type is acceptable; what fails is the value, because "3.5" is not a valid integer literal — that is a ValueError. TypeError is the trap: it would be raised if the type itself were unusable, as in "5" + 5. The line is grammatically valid, so it is not a SyntaxError, and every name in it is defined.In a try statement, when is the else clause executed?
Show answer
Answer: A — Only when the try block completes without raising any exception
else is the success branch: it runs only if the try block finished without an exception, which keeps code that depends on that success out of the try block. "Always" describes finally, not else. When an exception is caught, the except clause runs instead of else, and when none matches, neither except nor else runs — only finally, before the exception moves on.
Show the other 22 questions
What does the following code print?
def f(a, b):try:return a / bexcept ZeroDivisionError:return -1finally:print("done", end=" ")print(f(6, 0))Show answer
Answer: C — done -1
6 / 0 raises ZeroDivisionError, the except clause reaches return -1, and finally still runs before the function actually returns, printing "done " with a space. Only then does the outer print receive -1 and print it, giving done -1. Writing -1 alone assumes return skips finally, and "-1 done" gets the order backwards, as if the value were printed before the function finished.Consider: x = -3 followed by assert x >= 0, "negative". What happens when the assert statement runs?
Show answer
Answer: C — It raises an AssertionError with the message "negative"
assert evaluates its condition; -3 >= 0 is False, so Python raises AssertionError and attaches the message after the comma. Nothing is printed on its own — if the exception is not handled, the program stops with a traceback ending in AssertionError: negative. ValueError is a different exception that assert never raises, and assert only checks a condition; it never changes a variable.Assertion (A): A Python script with a syntax error on its last line does not print anything, even from the lines above the error. Reason (R): Syntax errors are detected when the code is parsed, before any statement is executed.
Show answer
Answer: A — Both A and R are true, and R is the correct explanation of A
Python reads and parses the whole script before running it, so a syntax error anywhere stops the program from starting; the print statements above the faulty line are never reached. That parsing step is exactly why A happens, so R explains A. Treating A as false confuses syntax errors with exceptions, which do let the earlier lines run because they arise only during execution.A programmer writes a bare except: clause first and an except ValueError: clause after it, under the same try. What happens?
Show answer
Answer: D — Python refuses to run the code: a bare except must be the last clause
A bare except catches every exception, so any clause after it could never be reached; Python treats that ordering as an error in the code itself and reports SyntaxError: default 'except:' must be last before running anything. The idea that the later clause is "simply never reached" is the tempting answer, but Python does not wait to discover that at run time, and only one except clause ever runs for an exception.In exception handling, what is meant by "catching" an exception?
Show answer
Answer: B — The runtime system finding and executing a suitable handler for it
When an error occurs, creating the exception object and handing it to the runtime system is throwing; the runtime system then searches for code that can handle it, and locating and running that handler is catching. Creating the object is throwing, the opposite end of the process. Syntax errors are found during parsing and are not caught by the program at all, and nothing about catching involves a log file.Which keyword is used in Python to raise an exception explicitly?
Show answer
Answer: A — raise
raise creates an exception on purpose. throw and catch belong to other languages, and except only handles an exception.The block of a try statement that is executed whether or not an exception occurs is:
Show answer
Answer: A — finally
finally always runs, which makes it the place for cleanup. else runs only when no exception occurs, the tempting option.Which exception is raised by the statement print(10 / 0)?
Show answer
Answer: A — ZeroDivisionError
Dividing by zero raises ZeroDivisionError. ValueError arises for an inappropriate value such as int("x"), and ArithmeticOverflow is not a Python exception.Using a variable that has never been assigned, such as print(total) with no earlier total, raises:
Show answer
Answer: A — NameError
An undefined name gives NameError. IndexError is for an invalid list position and KeyError for a missing dictionary key.What is the output of the following code?
try:print(10 // 2, end=" ")except ZeroDivisionError:print("Z", end=" ")else:print("E", end=" ")finally:print("F")Show answer
Answer: B — 5 E F
10 // 2 works, so except is skipped; the else block runs because no exception occurred, and finally always prints F, giving 5 E F. "5 Z F" runs the except that never triggers, and "5 F" forgets else.What is the output of the following code?
def check(n):if n < 0:raise ValueError("neg")return ntry:print(check(5), end=" ")print(check(-1), end=" ")except ValueError as e:print("Caught", e)Show answer
Answer: A — 5 Caught neg
check(5) prints 5; check(-1) raises ValueError, so its print never runs and the handler prints "Caught neg", giving 5 Caught neg. "Caught neg" alone forgets the 5 already printed, and "5 -1 Caught neg" pretends check(-1) returned.What is the output of the following code?
def f():try:return "A"finally:print("B", end="")print(f())Show answer
Answer: C — BA
The return value A is prepared, but finally still runs and prints B before the function returns, so the print shows B first and then A: BA. "AB" reverses the order and "A" forgets that finally always executes.Assertion (A): A finally block runs even when no exception occurs in the try block.
Reason (R): finally is meant for cleanup actions, such as closing a file, that must happen in every case.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Cleanup must happen with or without an exception, which is why finally always runs; R states the purpose. Option 2 is wrong because R explains A.Consider the following statements:
A. A try block can be followed by more than one except block.
B. The raise statement can be used to generate an exception.
C. A try block must always be followed by a finally block.
D. assert raises AssertionError when its condition is False.
Choose the correct answer:Show answer
Answer: A — A, B and D only
A, B and D are true. C is false because finally is optional; a try needs only an except or a finally, so option 4 is the trap.Match List I with List II:
List I:
A. ZeroDivisionError;
B. IndexError;
C. KeyError;
D. TypeError
List II:
1. "a" + 1;
2. lst[10] on a 3-item list;
3. 5 / 0;
4. d["z"] with no key zShow answer
Answer: A — A-3, B-2, C-4, D-1
5 / 0 gives ZeroDivisionError (3), an out-of-range index gives IndexError (2), a missing key gives KeyError (4) and adding a string to an integer gives TypeError (1). Option 2 swaps ZeroDivisionError and IndexError.What is the output of the following code?
d = {"a": 1}try:print(d["b"], end="")except KeyError:print("K", end="")except Exception:print("E", end="")print("!")Show answer
Answer: B — K!
d["b"] raises KeyError, and the first matching handler runs, printing K; execution then continues past the try statement and prints !, giving K!. "E!" picks the general handler although the specific one matches first.What is the output of the following code?
x = 0try:x += 1y = 10 / 0x += 10except ZeroDivisionError:x += 100else:x += 1000finally:x += 5print(x)Show answer
Answer: D — 106
x becomes 1, the division raises the error so x += 10 is skipped; except adds 100 (101), else is skipped, and finally adds 5, giving 106. 1106 wrongly runs else, 16 ignores except and 111 skips finally.What is the output of the following code?
try:try:int("x")except TypeError:print("T", end="")finally:print("F", end="")except ValueError:print("V", end="")Show answer
Answer: A — FV
int("x") raises ValueError, which the inner except TypeError does not match; the inner finally still prints F, and the exception then reaches the outer handler, printing V: FV. "V" forgets the inner finally and "TFV" assumes the inner handler matched.Assertion (A): An unhandled exception terminates the program and prints a traceback.
Reason (R): Python searches for a matching handler up the call stack, and when none is found the default handler stops the program.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
The search up the stack and the default handler are the mechanism behind the traceback, which R states. Option 2 is wrong.What is the output of the following code?
total = 0for v in ["4", "x", "6", "-2"]:try:total += int(v)except ValueError:continueprint(total)Show answer
Answer: C — 8
int("x") raises ValueError and is skipped by continue, so only 4, 6 and -2 are added: 8. 12 treats "-2" as 2 or ignores its sign, and 10 drops the -2.What is the output of the following code?
def div(a, b):try:return a / bexcept ZeroDivisionError:return -1print(div(7, 0) + div(8, 2))Show answer
Answer: B — 3.0
div(7, 0) returns -1 and div(8, 2) returns 4.0, so the sum is 3.0. "3" is an integer, but / always returns a float, and an error does not arise since the exception is handled.Which of the following statements about exceptions and syntax errors is correct?
Show answer
Answer: A — A syntax error is detected before the program runs, whereas an exception occurs while it runs
A syntax error stops the program from being compiled and so cannot be caught by a try block in the same code. Exceptions occur during execution, the reverse of option 3.