Exception Handling in C++

Level 5252 keystrokes

divide() throws a runtime_error when the divisor is 0. The first call prints 5; the second throws, and the catch block prints the error message.

C++ code

// Divides a by b
1double divide(double a, double b) {
// Checks the divisor first (dividing a double by 0 would silently give inf)
2 if (b == 0) {
// Throws an exception; the function stops here
3 throw runtime_error("Division by zero");
4 }
// Normal case: returns the quotient
5 return a / b;
6}
7
// Exceptions thrown inside try are handled by the catch below
8try {
// 10 / 2: prints 5
9 cout << divide(10, 2) << endl;
// Divisor is 0: divide throws, so this line prints nothing
10 cout << divide(5, 0) << endl;
// Catches runtime_error by const reference (no copy)
11} catch (const runtime_error& e) {
// what() returns the message: prints "Error: Division by zero"
12 cout << "Error: " << e.what() << endl;
13}

Output

5
Error: Division by zero
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 14
  • (× 7
  • )× 7
  • ;× 5
  • "× 4
  • {× 4
  • }× 4
  • ,× 3
  • _× 2
  • =× 2

More C++ examples at level 5

← C++ typing practice