C++ Primer 第五章 Statements
- 5.3. Conditional Statements
- 5.3.2. The switch Statement
- 5.4. Iterative Statements
- 5.4.3. Range for Statement
- 5.6. try Blocks and Exception Handling
- 5.6.1. A throw Expression
- 5.6.2. The try Block
- 5.6.3. Standard Exceptions
5.3. Conditional Statements
5.3.2. The switch Statement
Switch statements
enum Color
{
black,
white
}color;
switch (color)
{
case Color::black:
std::cout << "Black";
break;
case Color::white:
std::cout << "White";
break;
default:
std::cout << "Unknown";
break;
}
The expression is converted to integral type.
The one restriction on this expression is that it must evaluate to an integral type (that is, char, short, int, long, long long, or enum). Floating point variables, strings, and other non-integral types may not be used here.
The result of the expression is compared with the value associated with each case, which is declared using the case keyword and followed by a constant expression.
5.4. Iterative Statements
5.4.3. Range for Statement
for (declaration : expression)
statement
expression must represent a sequence, such as a braced initializer list , an array, or an object of a type such as vector or string that has begin and end members that return iterators.
declaration defines a variable. It must be possible to convert each element of the sequence to the variable’s type.
vector<int> v = {0,1,2,3,4,5,6,7,8,9};
// range variable must be a reference so we can write to the elements
for (auto &r : v) // for each element in v
r *= 2; // double the value of each element in v
5.6. try Blocks and Exception Handling
5.6.1. A throw Expression
// first check that the data are for the same item
if (item1.isbn() != item2.isbn())
throw runtime_error("Data must refer to same ISBN");
// if we're still here, the ISBNs are the same
cout << item1 + item2 << endl;
Throwing an exception terminates the current function and transfers control to a handler that will know how to handle this error.
The type runtime_error is one of the standard library exception types and is defined in the stdexcept header.
5.6.2. The try Block
try {
program-statements
} catch (exception-declaration) {
handler-statements
} catch (exception-declaration) {
handler-statements
} // . . .
Once the catch finishes, execution continues with the statement immediately following the last catch clause of the try block.
If no appropriate catch is found, execution is transferred to a library function named terminate.
The behavior of that function is system dependent but is guaranteed to stop further execution of the program.
5.6.3. Standard Exceptions
C++ 异常处理
The exception header defines the most general kind of exception class named exception.
The stdexcept header defines several general-purpose exception classes.