Tutorial by Examples

A try/catch block is used to catch exceptions. The code in the try section is the code that may throw an exception, and the code in the catch clause(s) handles the exception. #include <iostream> #include <string> #include <stdexcept> int main() { std::string str("foo&...
Sometimes you want to do something with the exception you catch (like write to log or print a warning) and let it bubble up to the upper scope to be handled. To do so, you can rethrow any exception you catch: try { ... // some code here } catch (const SomeException& e) { std::cout &l...
The only way to catch exception in initializer list: struct A : public B { A() try : B(), foo(1), bar(2) { // constructor body } catch (...) { // exceptions from the initializer list and constructor are caught here // if no exception is thrown h...
void function_with_try_block() try { // try block body } catch (...) { // catch block body } Which is equivalent to void function_with_try_block() { try { // try block body } catch (...) { // catch block body } } Note t...
struct A { ~A() noexcept(false) try { // destructor body } catch (...) { // exceptions of destructor body are caught here // if no exception is thrown here // then the caught exception is re-thrown. } }; Note that, although this...
In general, it is considered good practice to throw by value (rather than by pointer), but catch by (const) reference. try { // throw new std::runtime_error("Error!"); // Don't do this! // This creates an exception object // on the heap and would require you to catch the ...
C++11 During exception handling there is a common use case when you catch a generic exception from a low-level function (such as a filesystem error or data transfer error) and throw a more specific high-level exception which indicates that some high-level operation could not be performed (such as b...
c++17 C++17 introduces int std::uncaught_exceptions() (to replace the limited bool std::uncaught_exception()) to know how many exceptions are currently uncaught. That allows for a class to determine if it is destroyed during a stack unwinding or not. #include <exception> #include <strin...
You shouldn't throw raw values as exceptions, instead use one of the standard exception classes or make your own. Having your own exception class inherited from std::exception is a good way to go about it. Here's a custom exception class which directly inherits from std::exception: #include <ex...

Page 1 of 1