C++ Throw Keyword: Complete Exception Guide
In C++, the throw keyword is used to throw exceptions. It can be used with any throwable type, including basic types, custom types, and exceptions provided by the standard library.
The throw statement is typically used in conjunction with try and catch for exception handling. When a program reaches a throw statement, it immediately stops the current execution flow and transfers control to the closest catch block.
Example of grammar:
throw expression;
Expressions can be of any throwable type, such as integers, floating points, objects of custom types, and so on.
Here’s a simple example demonstrating how to use the “throw” statement:
#include <iostream>
int divide(int a, int b) {
if (b == 0) {
throw "除数不能为0"; // 抛出一个字符串异常
}
return a / b;
}
int main() {
try {
int result = divide(10, 0);
std::cout << "结果: " << result << std::endl;
}
catch (const char* message) {
std::cout << "捕获到异常: " << message << std::endl;
}
return 0;
}
In the example above, the divide function checks if the divisor is 0, and if so, it throws a string exception. In the main function, we use a try block to attempt to call the divide function and catch the exception in the catch block. If an exception is thrown, the catch block will execute and print the exception information.
In summary, “throw” is used to throw an exception and “catch” is used to catch and handle exceptions, which is a key part of the exception handling mechanism in C++.