Name

try statement — Handles exceptions in statements

Synopsis

               statement := try-block
               try-block ::= try compound-statement 
               handler-seq
               function-try-block ::= try [ctor-initializer] function-body 
               handler-seq
               handler-seq ::= handler | handler-seq 
               handler
               handler ::= catch ( exception-declaration ) compound-statement
               exception-declaration ::= type-specifier-seq declarator | 
    type-specifier-seq abstract-declarator | type-specifier-seq |  . . .

The try statement executes compound-statement, and if an exception is thrown in any of the statements within that compound statement (and not caught and handled by another try statement), the catch handlers are tested to see if any of them can handle the exception. Each catch handler is tested in turn. The first one to match the exception type handles the exception. If no handler matches, the exception propagates up the call stack to the next try statement. If there is no further try statement, terminate( ) is called.

Example

int main(  )try {
  run_program(  );
} catch(const exception& ex) {
  std::cerr << ex.what(  ) << '\n';
  abort(  );
} catch(...) {
  std::cerr << "Unknown exception. Program terminated.\n";
  abort(  );
}

See Also

catch, declarator, function, throw, type, Chapter 4, <exception> in Chapter 13

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.