How to throw a C++ exception?

C++ProgrammingServer Side Programming

Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Exception can be thrown anywhere within the code block. The keyword “throw” is used to throw an exception.

Here is an example of throw in C++ language,

Example

 Live Demo

#include <iostream>
using namespace std;

int display(int x, int y) {
   if( y == 0 ) {
      throw "Division by zero condition!";
   }
   return (x/y);
}

int main () {
   int a = 50;
   int b = 0;
   int c = 0;

   try {
      c = display(a, b);
      cout << c << endl;
   } catch (const char* msg) {
      cerr << msg << endl;
   }
   return 0;
}

Output

Here is the output

Division by zero condition!
raja
Published on 24-Oct-2018 14:04:42
Advertisements