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.\n";
cout << "Age is: " << myNum;
}
定义和用法
catch
关键字用于捕获由 try
语句生成的异常。
catch 语句允许你定义一个代码块,以便在 try 块中抛出异常时执行。在 catch 块中,可以访问包含异常的变量。
语法
catch(exceptionType exception) { code block }
exceptionType 是由 try
块抛出的异常的数据类型。exception 包含被抛出的异常。如果捕获到异常,则会执行代码块中的代码。
相关页面
throw
关键字用于创建异常。
try
关键字指定要从中捕获异常的代码块。
在我们的 C++ 异常教程 中了解更多关于异常的信息。