1. LPU MCA Semester 1
  2. CAB106
  3. Unit 5

CAB106 · Unit 5: Exception handling and file management

Types of errors and try, except, else and finally

15 practice questions

Key points

  • Syntax, runtime and logical errors are different things
  • try, except, else, finally and when each runs
  • The first matching except clause wins
  • finally runs even after return or continue

Errors fall into three groups. Syntax errors are found before any code runs. Runtime errors (exceptions) occur while the program runs, such as ValueError for int("abc"), IndexError for a position past the end of a list, KeyError for a missing dictionary key, ZeroDivisionError and TypeError. Logical errors let the program run but give wrong results, and Python cannot detect them.

BlockRuns when
tryAlways first; holds risky code
exceptA matching exception was raised
elseThe try block raised nothing
finallyAlways, for cleanup

Handlers are checked from top to bottom and the first match wins, so a general class such as LookupError placed before KeyError hides it. One clause can list several types as a tuple, and as e names the exception object. Exceptions that no handler matches propagate to the caller. A finally block runs even when the try block returns, and on every pass of a loop even after continue. Exceptions raised inside else are not caught by the same statement's handlers.

Exam trap: Python has no catch block, and else runs only when nothing was raised, unlike finally.

Try two questions

Question 1 · Tier 2, Understand

Which block of a try statement runs only when the try block raised no exception?

  1. finally
  2. except
  3. else
  4. catch
Show the answer

C. The else block runs after try finishes without an exception.

Why not A: finally runs whether or not an exception occurred.

Why not B: except runs only when an exception was raised.

Why not D: Python has no catch block; it uses except.

Question 2 · Tier 2, Understand

A program runs to the end without any error message but prints wrong results. What kind of error is this?

  1. A syntax error
  2. A runtime error
  3. An import error
  4. A logical error
Show the answer

D. Logical errors come from a flawed idea in the code, so Python cannot detect them.

Why not A: A syntax error stops the program before it runs.

Why not B: A runtime error stops the program with an exception.

Why not C: An import error happens when a module cannot be loaded.