Errors happen#
Even correct programs face problems at run time: the user types text instead of a number, a file is missing, the internet is down, someone divides by zero. Without handling, the program crashes with a traceback.
There are two kinds of errors:
| Syntax errors | Exceptions (runtime errors) |
|---|---|
| Code breaks Python's grammar | Code is valid, but something goes wrong while running |
| Found before the program runs | Happen during execution |
e.g. missing : or bracket |
e.g. dividing by zero, missing file |
| Must be fixed in the code | Can be handled with try/except |
Reading a traceback#
Traceback (most recent call last):
File "main.py", line 2, in <module>
x = int("ten")
ValueError: invalid literal for int() with base 10: 'ten'
Read it from the bottom: the last line gives the exception type (ValueError) and a message. The lines above show where it happened (file and line number).
Common built-in exceptions#
| Exception | When it happens | Example |
|---|---|---|
ZeroDivisionError |
dividing by zero | 10 / 0 |
ValueError |
right type, bad value | int("abc") |
TypeError |
wrong type for an operation | "5" + 5 |
NameError |
variable not defined | print(undefined_var) |
IndexError |
list index out of range | [1, 2][5] |
KeyError |
dict key not found | {"a": 1}["b"] |
AttributeError |
object has no such attribute | "abc".push() |
FileNotFoundError |
file doesn't exist | open("nofile.txt") |
ImportError / ModuleNotFoundError |
module can't be imported | import nonexistent |
try and except#
Put risky code in try. If an exception happens, Python jumps to the matching except block instead of crashing:
try / except को ऐसे समझें: "यह काम कोशिश करो (try); अगर कोई गड़बड़ हो जाए, तो program बंद करने की बजाय यह करो (except)।"
जैसे ATM - अगर आपने गलत PIN डाला, तो मशीन बंद नहीं हो जाती, बल्कि message दिखाती है "Wrong PIN, try again"। यही exception handling है - error को पकड़ना और समझदारी से संभालना, ताकि program crash न हो।
Catching specific exceptions#
Handle different problems differently:
Catch several types in one block with a tuple, and get the error message with as:
Avoid a bare except: or except Exception: that catches everything - it hides real bugs (even typos in variable names). Catch the specific exceptions you expect.
else and finally#
try:
# risky code
except SomeError:
# runs if that error happened
else:
# runs only if NO error happened
finally:
# ALWAYS runs - error or not
finally is used for clean-up: closing files, database connections, network sockets - things that must happen even if something fails.
Raising exceptions#
Use raise to signal an error in your own code - for example, when a function receives invalid input:
Custom exceptions#
For bigger programs, create your own exception classes (you'll learn classes in the OOP chapter):
A robust input pattern#
Summary#
- Exceptions are runtime errors; read tracebacks from the bottom.
try:risky code →except SpecificError:handle it.else:runs when no error occurred;finally:always runs (clean-up).- Catch specific exceptions; avoid bare
except:. raise ValueError("message")signals errors; subclassExceptionfor custom errors.