C++ Exception Handling C-PLUS-PLUS

C++ Exception Handling  

C++ Exception Handling

C++ Exception Handling

Exception handling in C++ consist of three keywords: trythrow and catch:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

The catch statement allows you to define a block of code to be executed if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

try {
  // Block of code to try
  throw exception; // Throw an exception when a problem arise
}
catch () {
  // Block of code to handle errors
}

You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes. 

Example

#include <iostream>
using namespace std;

int main() {
  try {
    int age = 15;
    if (age > 18) {
      cout << "Access granted - you are old enough.";
    } else {
      throw 505;
    }
  }
  catch (int myNum) {       //myNum is 505 which is thrown by throw keyword in above try block
    cout << "Access denied - You must be at least 18 years old.\n";
    cout << "Error number: " << myNum;  
  }
  return 0;
}
 

Output:

Access denied - You must be at least 18 years old.
Error number: 505

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries