You use a
try block to indicate which areas in your program that might throw
exceptions you want to handle immediately. You use a
function try block to indicate that you want to detect exceptions
in the entire body of a function.
Syntax - try Block .---------. V | >>-try--{--statements--}----handler-+--------------------------><
Syntax -- Function try Block .---------. V | >>-try--+----------------------------+--function_body----handler-+->< '-:--member_initializer_list-'
The following is an example of a function try block with a member initializer, a function try block and a try block:
#include <iostream> using namespace std; class E { public: const char* error; E(const char* arg) : error(arg) { } }; class A { public: int i; // A function try block with a member // initializer A() try : i(0) { throw E("Exception thrown in A()"); } catch (E& e) { cout << e.error << endl; } }; // A function try block void f() try { throw E("Exception thrown in f()"); } catch (E& e) { cout << e.error << endl; } void g() { throw E("Exception thrown in g()"); } int main() { f(); // A try block try { g(); } catch (E& e) { cout << e.error << endl; } try { A x; } catch(...) { } }
The following is the output of the above example:
Exception thrown in f() Exception thrown in g() Exception thrown in A()
The constructor of class A has a function try block with a member initializer. Function f() has a function try block. The main() function contains a try block.
Related References