throw Statement
catch Statement
try Statement
// How can shred::shred() // handle internal errors? shred s(e1, e2);
// How can shred::operator + () // handle internal errors? s1 = s1 + s2;
int e = f();
int f(int & err) { ... }
f();
if (err != 0) { ... }
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 lauches (throws) an exception.
throw expr throws the value expr as an exception.
return in syntax and semantics.
throw 1;
throw strack_trace("g()"));
throw new strack_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 {
char * cp;
}
catch (...) {
|
main() causes termination.
catch body is like any other
exception.
catch clause can rethrow an exception using throw.
try { ... }
catch (stack_trace & st) {
st.push_back("f()");
throw;
}
throw clause.
throw ( ex1, ex2, . . . )
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 13 October 2003.