throw Statement
catch Statement
try Statement
// How can widget::widget() // handle internal errors? widget w();
// How can widget::operator + () // handle internal errors? w1 = w1 + w2;
status e = f();
int f(status & err) { ... }
status err = error::none; f(); if (err != error::none) { ... }
int main () { int f() { int g() { f() g() if (b) g() } } }
main()
is called, and main()
calls f()
.
f()
then calls g()
.
f()
and g()
return.
main()
returns and the program ends.
f() { char * cp = new char [100]; FILE * inf = open(fname, O_RDONLY); g() delete [] cp; close(inf); }
g()
throws an exception, f()
terminates immediately.
throw
throws exceptions.
catch
catches exceptions.
try
delimits exception handling.
throw
Statementthrow
statement launches (throws, raises, signals) an
exception.
throw
expr throws the value expr as an exception.
return
in syntax and semantics.
throw 1; throw stack_trace("g()")); throw new stack_trace("g()"));
catch
Clausecatch (
type-spec [ name ] ) {
body
}
catch (exception_type ex) { std::cerr << ex.what(); }
catch(...) { }
catches any exception.
int main() { try { ... } catch (...) { std::cerr << "Uncaught exception!"; }
throw 1 catch (int e) {...} throw 'a' |
class red {} class mauve : red {} class blue throw red(); catch (red e) {...} |
try
Statementtry {
body }
catch-cls . . .
catch
body, continue after
the try
.
try
is not the scope of a catch
.
|
try { char * cp = new char [n]; } catch (...) {
|
main()
causes termination.
catch
body is like any other
exception.
try { try { body } catch ( exp ) { handler } catch ( exp ) { handler } } catch ( exp ) { handler } catch ( exp ) { handler }
''
catch
clause can rethrow an exception using throw
.
try { ... } catch (stack_trace & st) { st.push_back("f()"); throw; }
r-type name (
paras ) throw (
ex1, ex2, . . .
) {...}
int f() throw () { . . . }
throws nothing.
unexpected
exceptions
<exception>
.
<stdexcept>
.
class exception { public: exception() {} virtual ~exception() {} virtual const char* what() const { return "class exception"; } };
try { ... } catch (const std::exception & ex) { std::cerr << ex.what() << '\n'; }
<stdexcept>
defines three types of standard exceptions.
class logic_error : std::exception { public: explicit logic_error( const std::string &); };
std::exception
.
class my_exception : public std::logic_exception { public: explicit my_exception(const char *); const char * what() const; private: // whatever. };
class my_exception : public std::exception { public: explicit my_exception( const std::string & emsg) : std::out_of_range(emsg) { } };
std::exception
.
bad_alloc
in new
in
particular.
new
- this used to be standard.
auto_pointers
provide a means for automatic resource recovery on
exceptions.
This page last modified on 14 February 2004.