Computer Science · Ch 1 — Exception Handling in Python
Exceptions
Exceptions
An exception is not a syntax mistake. It is an error that happens during the execution of a program, even when the code is perfectly correct in terms of grammar and spelling. The textbook gives two classic examples: trying to open a file that does not exist, and attempting to divide a number by zero. Both statements are syntactically valid — Python can parse them without complaint — but when the program actually runs, the operation fails.
Such failures disrupt the normal flow of the program. If left unhandled, they cause the program to terminate abruptly, which is almost never what a user wants. Python treats these runtime errors as objects, and each one belongs to a specific class. When the error occurs, we say that an exception has been raised.
The programmer's job is to anticipate these situations during the design phase and write code that catches and handles the exception gracefully, so the program can either recover or exit cleanly. This is the core of exception handling.
The textbook explicitly points out that SyntaxError — the error shown when you write invalid Python grammar — is also an exception. However, it is a special case. All other exceptions arise only when the program is syntactically correct but something goes wrong at runtime.
To summarise the key points:
- An exception is a Python object that represents an error.
- It is raised when an error occurs during execution. …