Exception handling in C++

Level 4197 keystrokes

divide throws a C string when the divisor is 0; the try block prints 5, then the second call throws and the catch block prints the message.

C++ code

1int divide(int a, int b) {
// Throw a string literal (type const char*) when b is 0
2 if (b == 0) throw "Division by zero!";
// Integer division otherwise
3 return a / b;
4}
5
6try {
// 10 / 2: prints 5
7 cout << divide(10, 2) << endl;
// Throws before anything is printed; control jumps to catch
8 cout << divide(10, 0) << endl;
// Catches exceptions of type const char*
9} catch (const char* e) {
// Print Division by zero!
10 cout << e << endl;
11}

Output

5
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.

  • <× 12
  • ;× 5
  • (× 5
  • )× 5
  • ,× 3
  • {× 3
  • }× 3
  • "× 2
  • =× 2
  • !× 1

More C++ examples at level 4

← C++ typing practice