throw exception c++ code example

Example 1: c++ throw exception

#include 

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

Example 2: throw exception c++

#include 
#include 
#include 

using namespace std;

void MyFunc(int c)
{
    if (c > numeric_limits< char> ::max())
        throw invalid_argument("MyFunc argument too large.");
    //...
}

Example 3: declare and define exception c++

// using standard exceptions
#include 
#include 
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 4: c++ try

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

Example 5: c++ try

// exceptions
#include 
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << '\n';
  }
  return 0;
}

Example 6: c++ throw exception

// using standard exceptions
#include 
#include 
using namespace std;

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

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)
  {
    cout << e.what() << '\n';
  }
  return 0;
}

Tags: