try...catch...exception in C++
1 | int main(){ |
and if you want create classes for exceptions. You should add #include<exception> and inherit exception class, and then override the function “what”.
1 | #include<iostream> |
There are some standard exceptions in exception.h. These exceptions are:
bad_alloc
A bad_alloc is thrown by new if an allocation failure occurs.
bad_cast
A bad_cast is thrown by dynamic_cast when it fails with a referenced type.
bad_exception
A bad_exception is thrown when an exception type doesn’t match any catch
bad_typeid
A bad_typeid is thrown by typeid
ios_base::failure
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(…)
1 | try{ |
But when i == 0, the program will execute throw;, and it will exit and print:
terminate called without an active exceptionAborted
You should specify something to throw. throw; is only be used within catch clauses.
1 | try{ |
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.
1 | void foo() throw(int,bad_exception){ |
output is
I get unexpected exceptions! bad_exceptionIf 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.