c++ throw exception types code example
Example 1: declare and define exception c++
#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;
}
Example 2: exception handling c++
#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}