Skip to content

Computer Science · Ch 1 — Exception Handling in Python

Handling Exceptions

1.6

Handling Exceptions

Exception handling is the process of writing additional code in a program to deal with exceptions — those runtime errors that would otherwise crash the program abruptly. The goal is not just to prevent a crash, but to give the user a proper message or instruction when something goes wrong.

Every exception that can occur in a program must be handled by the programmer. If left unhandled, the program terminates suddenly, and the user sees an unfriendly traceback message. By handling exceptions, you make your program robust and user-friendly.

The core idea is simple: you anticipate that a certain block of code might raise an exception, and you write a separate block of code that runs only if that exception occurs. This way, the program does not stop dead — it executes the handling code and then continues (or exits gracefully).

Note

Exception handling is not about preventing errors from happening; it is about controlling what happens when they do happen.

The textbook introduces this concept as the foundation for the rest of the chapter. The actual syntax — using try, except, else, and finally — is covered in later sections. For now, understand that the programmer's responsibility is to identify which parts of the code are risky and to provide fallback behaviour for each possible exception.

  • Why handle exceptions? To avoid abrupt program crashes. …