try, except, else and finally.
try is what you attempt first, except is the back-up plan, and finally is the clean-up that must always happen.
3.1 Why do we need Exception Handling?
Real programs run in the real world — users type wrong inputs, files disappear, networks fail, division by zero happens. If any of these occur, Python stops the program and shows an angry red traceback. That is fine for a programmer debugging at home, but it is terrible for an end-user who just wanted to enter their marks.
That one mistake crashed the whole program. Compare the same code with exception handling:
The program still warned the user, but it did not crash. That is the power of exception handling.
- Programs become robust — they survive bad input.
- Error messages can be friendly (no scary traceback).
- Clean-up work (closing files, disconnecting from the database) always runs.
- Error-handling code is separated from normal code — easier to read.
3.2 Recap — Errors vs Exceptions
You met this in Class XI (§6 of the revision chapter). Here is the short version you need for this chapter.
| Syntax error | Exception (run-time error) | |
|---|---|---|
| When it happens | Before the program starts | While the program is running |
| Example | prin("hi") | 1 / 0 → ZeroDivisionError |
| Can you catch it? | No — fix the code | Yes — use try/except |
try/except. Syntax errors must be corrected by you before the program will even run.
3.2.1 Common built-in exceptions you will meet
| Exception | Triggered when… |
|---|---|
ZeroDivisionError | Divide or mod by zero |
ValueError | Right type, wrong value — int("abc") |
TypeError | Wrong type — "x" + 2 |
NameError | Variable not defined |
IndexError | List index out of range |
KeyError | Missing dictionary key |
FileNotFoundError | Opening a file that doesn’t exist |
IOError / OSError | General input/output failure |
AttributeError | Using a method/attribute the object doesn’t have |
ImportError / ModuleNotFoundError | import something_missing |
3.3 The try … except Block
3.3.1 The basic syntax
Python executes the try block. If an exception occurs, Python jumps straight to the matching except block. If no exception occurs, the except block is skipped.
3.3.2 Catching a specific exception — always preferred
except should name the specific exception it handles. This way, a different kind of bug is not accidentally swallowed and hidden.
3.3.3 Catching multiple exceptions in one block
If the response is the same for several exceptions, group them in a tuple:
3.3.4 A generic except (use sparingly)
Writing except: or except Exception: catches every exception. This is a last resort — use it only when you genuinely don’t know which exception can occur.
except: — it will even swallow KeyboardInterrupt (Ctrl-C) and SystemExit, making your program impossible to stop. Always catch Exception instead, or a more specific type.
3.3.5 Getting the error message — as e
Use as variable after the exception name to capture the exception object. You can then read its message with str(e) or just print it.
3.4 The else Clause
An optional block that runs only if no exception was raised in the try block. Useful when you want to keep the try block tiny and put the “success path” in else.
else? It keeps the risky line alone in the try. If we had put print(n*n) inside try and n*n happened to raise some other error, the except ValueError would wrongly be blamed.
3.5 The finally Clause
An optional block that runs no matter what — whether the try succeeded, an exception was caught, or an exception was re-raised. Perfect for clean-up work like closing a file or a database connection.
finally is guaranteed to run — even if the try contains return, break or a raise. Use it for actions that must happen before the program moves on.
3.6 The Complete try / except / else / finally Flow
3.6.1 One-shot example combining all four
3.7 The raise Statement
raise is how you can throw an exception on purpose. Use it when your function detects an invalid situation that its caller ought to handle.
3.7.1 Raising a built-in exception
3.7.2 Re-raising the current exception
Sometimes a function wants to log the error but still let the caller know something went wrong. Use a bare raise inside except to re-throw the same exception.
3.7.3 Choosing the right exception class
| Situation | Use |
|---|---|
| Value has the right type but a wrong value | ValueError |
| Wrong type was passed | TypeError |
| Key missing from a dictionary | KeyError |
| Index out of range | IndexError |
| Operation not supported in this state | RuntimeError |
3.8 Nested try Blocks
A try can contain another try. Useful when the inner operation has its own specific failure that you want to handle before falling back to the outer handler.
3.9 CBSE-style Worked Programs
3.9.1 Safe division
3.9.2 Retry until the user enters a valid number
3.9.3 Handle a missing dictionary key
3.9.4 Opening a file safely
3.9.5 Validating a mark between 0 and 100 using raise
3.9.6 Summation with per-entry error reporting
3.9.7 Calculator with menu
3.10 Common Mistakes to Avoid
| # | Mistake | Fix |
|---|---|---|
| 1 | Using a bare except: that silently swallows every error | Catch the specific exception — or at least except Exception as e and print e |
| 2 | Putting “success” code inside try so wrong errors get blamed | Put only the risky line in try; put success code in else |
| 3 | Forgetting to close a file when an exception happens | Close it in finally, or use with open(…) as f: |
| 4 | Raising a plain Exception when a more specific class fits | Use ValueError, TypeError, KeyError, etc. |
| 5 | Using try/except to hide genuine bugs in your code | Exceptions are for external failures (bad input, missing file), not for logic errors |
| 6 | Handling the wrong exception type, so the real one still crashes | Read the traceback — the last line names the exact exception to catch |
Quick-revision summary
- An exception is a run-time error. Syntax errors cannot be handled — you must fix the code first.
trywraps the risky code;exceptcatches one (or more) exception types and responds.except (A, B):catches either exception;except E as e:captures the exception object for its message.elseruns only when thetrysucceeds (no exception).finallyalways runs — ideal for clean-up (closing files, disconnecting).raise ExceptionType("msg")throws an exception on purpose; a bareraisere-throws the current exception.- Prefer specific exception classes; avoid bare
except:. - Use
try/exceptfor external failures; do not use it to hide bugs in your own logic.