C++ 异常处理
C++ 异常
在执行 C++ 代码时,可能会发生不同的错误:程序员编写的编码错误、错误输入引起的错误或其他不可预见的事情。
当发生错误时,C++ 通常会停止并生成错误消息。这个术语的技术术语是:C++ 会抛出异常(抛出错误)。
C++ try 与 catch
C++ 中的异常处理由三个关键字组成: try, throw 与 catch:
try 语句让您定义要在执行时测试错误的代码块。
throw 关键字在检测到问题时引发异常,这让我们可以创建自定义错误。
catch 语句允许您定义要执行的代码块(如果 try 块中出现错误)。
try 与 catch 关键字成对出现:
实例
try {// 要尝试的代码块throw exception; // 出现问题时抛出异常}catch () {// 处理错误的代码块}
思考下面的例子:
实例
#include <iostream>using namespace std;int main() {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;}return 0;}
实例解释
我们使用 try 代码块测试一些代码:如果 age 变量小于 18,我们将抛出一个异常,并在 catch 块中处理它。
在 catch 代码块中,我们捕获错误并进行处理。catch 语句使用一个 parameter 参数:在我们的实例中,我们使用一个 int 变量(myNum)(因为我们在 try 代码块(age)中抛出一个 int 类型的异常)来输出 age 的值。
如果没有发生错误(例如,如果 age 是 20 岁而不是 15 岁,这意味着年龄将大于 18 岁),则跳过 catch 块:
实例
#include <iostream>using namespace std;int main() {try {int age = 20;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;}return 0;}
您还可以使用 throw 关键字输出参考数字,例如用于自定义错误号/代码:
实例
#include <iostream>using namespace std;int main() {try {int age = 15;if (age >= 18) {cout << "Access granted - you are old enough.";} else {throw 505;}}catch (int myNum) {cout << "Access denied - You must be at least 18 years old.\n";cout << "Error number: " << myNum;}return 0;}
处理任务类型的异常 (…)
如果不知道 try 代码块中使用的 throw 抛出的 类型,可以在 catch 块内部使用 "三点" 语法(…),它将处理任何类型的异常:
实例
#include <iostream>using namespace std;int main() {try {int age = 15;if (age >= 18) {cout << "Access granted - you are old enough.";} else {throw 505;}}catch (...) {cout << "Access denied - You must be at least 18 years old.\n";}return 0;}