`try`、`catch` 和 `throw` 是 C++、Java 和 Python 等编程语言中用于异常处理的关键字。
在 try 块中,您编写的代码可能会引发异常。 如果在 try 块中抛出异常,程序将跳转到最近匹配的可以处理异常的 catch 块。
`catch` 块指定它可以处理的异常类型,并包含在抛出该类型异常时执行的代码。 如果抛出的异常类型与 `catch` 块中指定的类型匹配,则执行 `catch` 块中的代码。
`throw` 关键字用于从 `try` 块中显式抛出异常。 您可以抛出从“std::exception”类 (C++) 派生的任何对象,或任何实现“Throwable”接口 (Java) 的对象。
以下是如何在 C++ 中使用“try”、“catch”和“throw”的示例:
#include <iostream>
#include <stdexcept>
int divide(int x, int y) {
if (y == 0) {
throw std::invalid_argument("divide by zero");
}
return x / y;
}
int main() {
int a = 10, b = 0;
try {
int result = divide(a, b);
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
在此示例中,“divide()”函数采用两个整数“x”和“y”,如果“y”为零,则抛出“std::invalid_argument”类型的异常。 在 `main()` 函数中,我们在 `try` 块中调用 `divide(a, b)`,并在 `catch` 块中捕获任何类型为 `std::exception` 的异常。 如果抛出异常,程序会向标准错误流打印一条错误消息。
总之,`try`、`catch` 和 `throw` 是异常处理中用于处理程序中的错误情况并提供错误报告和恢复机制的关键字。