try, except, else and finally

Handling exceptions and recovering from them.

Computer Science/Informatics Practices5 questions

The essentials

Exception handling lets a program catch an error and respond, instead of crashing. Code that may cause an exception is placed in a try block. If an exception occurs, Python skips the rest of the try block and looks for a matching except block. This is called catching the exception.

Key points

  • Structure: try → one or more except blocks → optional else → optional finally.
  • except ExceptionName: handles only that type. Several except blocks can handle different exceptions; the first matching one runs.
  • except: with no name catches any exception; it should be placed last.
  • except ValueError as e: gives access to the exception message through e.
  • else: runs only if the try block finishes without any exception.
  • finally: always runs, whether or not an exception occurred and whether or not it was handled. It is used for clean-up such as closing files.
  • If no except block matches, the exception is passed upward; finally still runs before the program stops.
  • A handler can ask the user to re-enter data in a loop, letting the program recover.

Exam tips

  • Output questions: write down which blocks run. With an exception: try (partly) → matching except → finally. Without an exception: try → else → finally.
  • Code inside try after the error line is never executed.

Common mistakes

  • Thinking else runs after an except block. It runs only when there is no exception.
  • Thinking finally is skipped when a return statement is in try. finally still runs.

Practice questions

Practice this topic