📜  C++ try-catch(1)

📅  最后修改于: 2023-12-03 14:39:53.530000             🧑  作者: Mango

C++中的try-catch

在C++中,try-catch是一种异常处理机制。当程序出现错误时,异常被抛出并且程序会在try块中寻找适合处理该异常的catch块,从而避免程序直接崩溃。本文将详细介绍C++中try-catch的用法和实例。

try-catch语法

try-catch语法如下:

try {
    // 可能会抛出异常的代码
}
catch (ExceptionType e) {
    // 处理异常的代码
}
  • try 块:尝试执行可能会抛出异常的代码块
  • catch 块:当有异常被抛出时,会在这里寻找对应的异常类型并进行处理
  • ExceptionType:表示抛出异常的类型,该参数可以是定义好的任何类型
try-catch实例

下面是一个使用try-catch的简单实例:

#include <iostream>
using namespace std;

int main()
{
   int a = 10;
   int b = 0;
   double result;
   
   try {
        if( b == 0 ) {
            throw "division by zero";//抛出异常
        }
        result = a / b;
        cout << "The result is: " << result << endl;
   }
   catch (const char* e)
   {
        cerr << "Error: " << e << endl;
   }

   return 0;
}

在这个例子中,我们试图计算10除以0的结果。这样的操作是非法的,所以出现了一个异常并由throw语句抛出。在catch块中,我们使用const char*类型来捕捉这个异常。最终会输出“Error: division by zero”。

多个catch块

如果一个try块可能会抛出多种不同的异常,那么在程序中可以设置多个catch块,分别用来处理每种不同的异常。下面是一个使用多个catch块的实例:

#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

void something_wrong()
{
    throw "Something is wrong!";
}

int main()
{
    try {   
        // 使用throw语句来抛出不同的异常
        something_wrong();
    } catch (const char* e) {
        cerr << "Error occurred: " << e << endl;
    } catch (const exception& e) {
        cerr << "Error occurred: " << e.what() << endl;
    } catch (...) {
        cerr << "Unknown exception occurred!" << endl;
    }   
    //这是最后一个catch块,所以可以处理任何无法处理的异常

    return 0;
}

其中,第一个catch块会捕获到const char*类型的异常,而第二个catch块会捕获到std::exception类型的异常。最后一个catch块是通用的异常处理块,可以捕获任何类型的异常,因为它没有声明任何特定的异常类型。

结论

try-catch机制使得我们可以更好地处理程序运行时可能出现的异常情况,从而避免程序崩溃,提高程序的健壮性。通过本文,我们也可以更好地理解和掌握在C++中使用try-catch机制的方法和技巧。