if you will throw something, you should catch it as the same type. like following:
and if you want create classes for exceptions. You should add #include<exception> and inherit exception class, and then override the function “what“.
There are some standard exceptions in exception.h. These exceptions are:
A bad_alloc is thrown by new if an allocation failure occurs.
A bad_cast is thrown by dynamic_cast when it fails with a referenced type.
A bad_exception is thrown when an exception type doesn’t match any catch
A bad_typeid is thrown by typeid
An ios_base::failure is thrown by functions in the iostream library.
in #include<stdexecpt> can use these exception:
class logic_error; // : public exception
class domain_error; // : public logic_error
class invalid_argument; // : public logic_error
class length_error; // : public logic_error
class out_of_range; // : public logic_error
class runtime_error; // : public exception
class range_error; // : public runtime_error
class overflow_error; // : public runtime_error
class underflow_error; // : public runtime_error
If you don’t know which kind of exception will occur. you should use catch(…)
But when i == 0, the program will execute throw;, and it will exit and print:
terminate called without an active exception
You should specify something to throw. throw; is only be used within catch clauses.
you can declare your functions using throw(). But it is just declare! you can throw everything! But you declare it will throw bad_exception, and use set_unexpected(), it will process some unexpected exceptions.
I get unexpected exceptions!
If the program or your function can not process some kind of situation. you should throw something out. Sometime, someone argued that it will reduce the usability. But If you don’t stop the processing(program or function), it will create a disaster. Remember, by all means, throw it! But should we catch those exceptions and how we catch those? e….as your wish. Some bug will not appear, if you use not appropriate catch and process those exceptions in unsuitable way. If your program have some bug, and it is difficult to find, please delete all catches!
In some languages which have finally clauses. But in c++, it dose not have finally clauses.