Answers for "how to throw exception in cpp"

C++
5

c++ throw exception

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}
Posted by: Guest on May-01-2020
3

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;
}
Posted by: Guest on September-16-2020
3

c++ throw exception

// 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;

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)
  {
    cout << e.what() << 'n';
  }
  return 0;
}
Posted by: Guest on May-01-2020

Browse Popular Code Answers by Language