Skip to content

Computer Science · Ch 1 — Exception Handling in Python

Introduction

1.1

Introduction

When you write a Python program, you expect it to run smoothly and give the correct output. But sometimes, things go wrong. The program might not run at all, or it might run but produce unexpected results, or it might behave in a strange, abnormal way.

These problems are not random. They happen because of specific mistakes in the code. Python classifies these mistakes into three broad categories:

  • Syntax errors: These are violations of the language's grammar rules. For example, forgetting a colon at the end of an if statement, or missing a closing bracket. Python catches these errors immediately, before the program even starts running. The program simply will not execute.

  • Runtime errors: These occur while the program is running. The code might be syntactically correct, but something goes wrong during execution — like trying to divide a number by zero, or trying to open a file that does not exist. When this happens, the program crashes abruptly.

  • Logical errors: These are the trickiest. The program runs without crashing, and it does not show any error message. But the output is wrong. The logic of the code is flawed — for instance, using a multiplication sign where you needed addition. The computer does exactly what you told it to do, but what you told it to do was not what you intended.

In Python, the runtime errors that cause a program to crash are called exceptions. The key idea is that exceptions are normally triggered automatically by Python when something goes wrong at runtime.

However, Python also gives you the power to do two more things with exceptions. First, you can forcefully trigger an exception yourself, even when nothing is technically wrong — this is useful for signalling special conditions in your program. Second, you can handle exceptions through program code. Instead of letting the program crash, you can write code that catches the exception and responds to it gracefully, allowing the program to continue or shut down cleanly.

This chapter is about learning how to do exactly that — how to handle exceptions in Python programs.