Why exceptions?#
In C, functions report errors with special return values (-1, NULL) that callers often forget to check. C++ exceptions separate the normal code from the error-handling code, and an error cannot be silently ignored - if nobody handles it, the program stops.
try {
// code that might fail
throw something; // signal an error
} catch (const Type &e) {
// handle it
}
Withdrew 1200, balance 3800 Invalid: Amount must be positive Failed: Insufficient balance Withdrew 800, balance 3000
When throw runs, the function stops immediately; C++ jumps to the nearest matching catch, destroying local objects on the way (stack unwinding - destructors still run, so RAII resources are released).
Exception = program चलते समय आई गड़बड़ी (जैसे zero से भाग, file न मिलना, गलत input)। जहाँ गड़बड़ी पता चले वहाँ throw करें, और जहाँ उसे संभालना हो वहाँ try { } catch { } लगाएँ। इससे error handling का code main logic से अलग और साफ़ रहता है।
Standard exception classes#
All standard exceptions derive from std::exception, which has a what() function returning the message.
Class (<stdexcept>) |
Typical meaning |
|---|---|
invalid_argument |
a bad parameter value |
out_of_range |
index/key outside the valid range (vector::at) |
runtime_error |
errors only detectable while running |
logic_error |
a bug in the program logic |
bad_alloc (<new>) |
new could not allocate memory |
out_of_range caught invalid_argument caught from stoi something was thrown
Order matters: put more specific catch blocks before general ones (catch (const exception &e) last, catch (...) very last). The first matching handler wins.
Custom exception classes#
Derive from std::exception (or one of its children) to create meaningful errors for your program:
91 -> A 105 -> Invalid marks: 105 (must be 0-100) 64 -> C
File handling with fstream#
Class (<fstream>) |
Purpose |
|---|---|
ofstream |
write to a file |
ifstream |
read from a file |
fstream |
read and write |
They work exactly like cout and cin: << writes, >> and getline read. The file is closed automatically when the stream object is destroyed (RAII again).
Aarav -> 82 Diya -> 91 Kabir -> 77 Average: 83.3333
Appending and checking for errors#
1: start 2: user login 3: report generated Could not open does_not_exist.txt
| Mode flag | Meaning |
|---|---|
ios::out |
write (default for ofstream; erases the file) |
ios::app |
append to the end |
ios::in |
read (default for ifstream) |
ios::binary |
binary mode (no newline translation) |
Summary#
throwsignals an error;try/catchhandles it; uncaught exceptions end the program.- Use the standard classes (
invalid_argument,out_of_range,runtime_error) or derive your own from them; catch byconst &. ofstreamwrites,ifstreamreads,fstreamdoes both; files close automatically.- Use
ios::appto append, and always checkif (!file)after opening.