Skip to content

Instantly share code, notes, and snippets.

@ElemarJR
Created December 1, 2012 17:37
Show Gist options
  • Select an option

  • Save ElemarJR/4183382 to your computer and use it in GitHub Desktop.

Select an option

Save ElemarJR/4183382 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stdexcept>
using namespace std;
int safeDivide(int a, int b) {
if (b == 0)
throw invalid_argument("Division by 0");
return a / b;
}
int main() {
try {
cout
<< "10 / 2 = "
<< safeDivide(10, 2)
<< endl;
cout
<< "5 / 0 = "
<< safeDivide(5, 0) // throws exceptions
<< endl;
cout
<< "(never executed) 6 / 3 = "
<< safeDivide(6, 3)
<< endl;
} catch (const invalid_argument& e)
{
cout << "caught exception: " << e.what() << endl;
}
return 0;
}
@aardvarrk
Copy link
Copy Markdown

std::domain_error is probably more appropriate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment