⚡0 XP🔥0

Exceptions and File Handling

Lesson 11 of 12 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs C++

Handle errors with try, catch and throw, standard exception classes, custom exceptions, and read/write files with ifstream, ofstream and fstream.

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
}
▶ Try it YourselfC++
Ctrl + Enter to run
Output
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
▶ Try it YourselfC++
Ctrl + Enter to run
Output
out_of_range caught
invalid_argument caught from stoi
something was thrown
Tip

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:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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).

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Aarav -> 82
Diya -> 91
Kabir -> 77
Average: 83.3333

Appending and checking for errors#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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#

  • throw signals an error; try/catch handles it; uncaught exceptions end the program.
  • Use the standard classes (invalid_argument, out_of_range, runtime_error) or derive your own from them; catch by const &.
  • ofstream writes, ifstream reads, fstream does both; files close automatically.
  • Use ios::app to append, and always check if (!file) after opening.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Safe division

Write double divide(double a, double b) that throws invalid_argument("Division by zero") when b is 0. main reads pairs until end of input and prints the result or Error: Division by zero:

10 / 4 = 2.5
Error: Division by zero
9 / 3 = 3
Test input:
10 4
5 0
9 3
Expected output:
10 / 4 = 2.5
Error: Division by zero
9 / 3 = 3
2

Save and total a price list

Write three items with prices to prices.txt using ofstream (one name price per line), then read the file back with ifstream and print each line and the total:

Pen 10
Notebook 45
Bag 850
Total: 905
Expected output:
Pen 10
Notebook 45
Bag 850
Total: 905

Quick Quiz

Q1.

What happens when an exception is thrown and never caught?

Q2.

Why catch exceptions by const &?

Q3.

Which class is used to write to a file?

Q4.

What does catch (...) catch?