Note 10.9.1.
In this book, we will not worry too much about differentiating the various types of exception. Instead, we will generally just catch
exception
.
exception
is a broad category that includes many different more specific types of exception. Here are a few examples:out_of_range
A parameter specifies a bad index.system_error
An error happened with something like reading a file.logic_error
Some violation of the internal logic of the program.exception
, it includes all of those different types. But it is possible to catch more specific types. It is also possible to catch multiple different types of exception and respond differently to each:
try {
// something that could go bad in different ways
} catch (const out_of_range& e) {
// handle out_of_range exception
} catch (const system_error& e) {
// handle system_error exception
} catch (const exception& e) {
// handle other exceptions
} catch (...) {
// handle all other exceptions
}
catch
blocks attached to a single try
, they will be checked in order until one matches. Once a catch
handles the exception, the rest of the catches are ignored. So the most specific catch
should be first, followed by less specific ones. Thus we have exception
after the other two more specific exception types.
catch
in this sample specifies ...
. That is a way to catch absolutely anything that was thrown. Instead of throwing one of the standard exception
types, code can throw its own custom exception types, or some other type of data completely. The ...
will catch any of those things.
catch
matches what was thrown, then the exception will propagate up to the next function as if there was no catch
.
exception
.