LearnWave
Learn it. Master it.

Exception Handling in Python

Catching exceptions

Write try-except blocks for likely errors.

Without exception handling, one error stops the whole program: every line after it is never run. Exception handling means managing an error so that the rest of the program keeps working.

Why it matters:

  • It prevents crashes: the program does not stop suddenly.
  • It handles errors gracefully: the user gets a clear message instead of a confusing traceback, and the program can take another action.
  • It helps debugging: it shows the type and place of the error.
  • It keeps the main logic of the program separate from the error-handling code, making the program more reliable and professional. It is essential in real applications that read files, take user input, use networks or databases.

What happens behind the scenes:

  • When an error occurs, Python creates an exception object with information about it, and hands it to the runtime system. This is throwing the exception.
  • The runtime system searches for a piece of code that can handle it, called a handler. It looks first in the current function, then in the functions that called it, going back through the call stack in reverse order.
  • When it finds a suitable handler, it runs it. This is catching the exception.
  • If no handler is found anywhere, the program stops.

In Python, the statements that might cause an error go inside a try block, and the code that handles each error goes in an except block:

try: (risky statements) except ZeroDivisionError: (what to do instead)

If an exception happens in the try block, Python skips the rest of the try block and jumps to the matching except block. If no exception happens, the except blocks are skipped. For example, if the user enters 0 and the program computes 50/denom, the ZeroDivisionError handler prints a friendly message, and the program carries on.

One try block can have several except blocks, one for each kind of error. An except with no exception name catches any other exception, so it should be placed last, after all the specific ones.

Put what may fail in try; handle what you expect in except.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.