I know the difference in handling of both of these catches, but what does it take for the ellipse to catch something the std::exception catch wouldn\'t catch?
For ex
While it's definitely a good idea to do so, you don't have to derive your custom exceptions from std::exception
. C++ allows you to throw practically any object type.
So throw 1;
will not be handled by your first handler, for example. And neither will...
class MyCustomException { // Doesn't derive
///
};
... if it was thrown.
As written, the throw
statement throws an object whose type is derived from std::exception
, so it's caught by the first catch
clause. If you change the throw to throw 3;
the exception will be caught by the second catch
clause, not the first.
catch(const std::exception& e)
Will catch std exceptions only.
catch(...)
Will catch everything there after.
You can handle integers and other types (http://www.cplusplus.com/doc/tutorial/exceptions/)
For example:
catch(int e)
You probably meant:
throw std::runtime_error("runtime error!"); // not std::runtime
The std::runtime_error is derived from the std::exception so your first catch block is fired up as it catches exceptions of type std::exception
. And there you probably meant:
std::cout << "Exception: " << e.what(); // not e
If you threw anything else other than the std::run_time
or std::exception
and its derivatives, the second catch
block would be triggered. Useful reading from the C++ FAQ:
What should I throw?