
Exception Example
By: a guest on
Apr 29th, 2012 | syntax:
C++ | size: 0.83 KB | hits: 21 | expires: Never
#include <iostream>
#include <stdexcept>
using namespace std;
void doSomething(int);
void doSomethingElse(int);
int main()
{
try
{
cout << "doSomething(5);" << endl;
doSomething(5);
cout << "doSomething(11);" << endl;
doSomething(11);
}
catch (invalid_argument e)
{
cerr << "Error: " << e.what() << endl;
}
try
{
cout << "doSomething(0);" << endl;
doSomething(0);
}
catch (invalid_argument e)
{
cerr << "Error: " << e.what() << endl;
}
return 0;
}
void doSomething(int x)
{
if (x > 10)
throw invalid_argument("X is greater than 10.");
doSomethingElse(x);
}
void doSomethingElse(int x)
{
if (x == 0)
throw invalid_argument("X is equal to 0.");
}