exception handler c++ code example

Example 1: declare and define exception c++

// using standard exceptions
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception {
  virtual const char* what() const throw() {
    return "My exception happened";
  }
} myex; // declare instance of "myexception" named "myex"

int main () {
  try {
    throw myex; // alternatively use: throw myexception();
  } catch (exception& e) { // to be more specific use: (myexception& e)
    cout << e.what() << '\n';
  }
  return 0;
}

Example 2: c++ try

try {
	//do
} catch (...){
	//if error do
}

Tags:

Cpp Example