- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 211字
- 2021-06-10 18:28:04
Specifying exceptions
Functions can also be marked to indicate whether they will throw an exception. More details about exceptions will be given in Chapter 7, Diagnostics and Debugging, but there are two syntaxes you need to be aware of.
Earlier versions of C++ allowed you to use the throw specifier on a function in three ways: firstly, you can provide a comma separated list of the types of the exceptions that may be thrown by code in the function; secondly, you can provide an ellipsis (...) which means that the function may throw any exception; and thirdly, you can provide an empty pair of parentheses, which means the function will not throw exceptions. The syntax looks like this:
int calculate(int param) throw(overflow_error)
{
// do something which potentially may overflow
}
The throw specifier has been deprecated in C++11 largely because the ability to indicate the type of exception was not useful. However, the version of throw that indicates that no exception will be thrown was found to be useful because it enables a compiler to optimize code by providing no code infrastructure to handle exceptions. C++11 retains this behavior with the noexcept specifier:
// C++11 style:
int increment(int param) noexcept
{
// check the parameter and handle overflow appropriately
}