C++ catch 关键字
示例
使用 try catch 处理错误:
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.
";
cout << "Age is: " << myNum;
}
定义和用法
catch关键字用于捕获由try语句生成的异常。
catch语句允许您定义一段代码块,当try代码块中抛出异常时,该代码块将被执行。在catch代码块中,可以使用一个包含异常的变量。
语法
catch(exceptionType exception) { code block }
exceptionType 是 try 代码块抛出的异常的数据类型。exception 包含抛出的异常。如果捕获到异常,则会执行代码块中编写的代码。
相关页面
throw关键字用于创建异常。
try关键字用于指定捕获异常的代码块。
阅读更多关于异常的信息,请参阅我们的C++异常教程。

