1#include <stdexcept>
2
3int compare( int a, int b ) {
4 if ( a < 0 || b < 0 ) {
5 throw std::invalid_argument( "received negative value" );
6 }
7}
1//throw "throws" an exception.
2
3It is usually used like:
4
5if(something isnt right){
6 throw somethingee;
7}
8
9/*(std::)*/cout << somethingee;
1// using standard exceptions
2#include <iostream>
3#include <exception>
4using namespace std;
5
6class myexception: public exception {
7 virtual const char* what() const throw() {
8 return "My exception happened";
9 }
10} myex; // declare instance of "myexception" named "myex"
11
12int main () {
13 try {
14 throw myex; // alternatively use: throw myexception();
15 } catch (exception& e) { // to be more specific use: (myexception& e)
16 cout << e.what() << '\n';
17 }
18 return 0;
19}
1#include <stdexcept>
2#include <limits>
3#include <iostream>
4
5using namespace std;
6
7void MyFunc(int c)
8{
9 if (c > numeric_limits< char> ::max())
10 throw invalid_argument("MyFunc argument too large.");
11 //...
12}
1// using standard exceptions
2#include <iostream>
3#include <exception>
4using namespace std;
5
6class myexception: public exception
7{
8 virtual const char* what() const throw()
9 {
10 return "My exception happened";
11 }
12} myex;
13
14int main () {
15 try
16 {
17 throw myex;
18 }
19 catch (exception& e)
20 {
21 cout << e.what() << '\n';
22 }
23 return 0;
24}