首页 > 文章列表 > C++ 函数异常处理中如何捕获特定类型的异常?

C++ 函数异常处理中如何捕获特定类型的异常?

异常处理 特定类型异常
217 2024-04-23

C++ 中捕获特定类型异常的方法:使用 try-catch 块。在 catch 子句中指定要捕获的异常类型,如 catch (const std::runtime_error& e)。实战案例中,read_file() 函数通过抛出 std::runtime_error 来处理文件不存在的情况,并使用 try-catch 块来捕获此异常并打印错误消息。

C++ 函数异常处理中如何捕获特定类型的异常?

C++ 函数异常处理中捕获特定类型的异常

在 C++ 中,使用 try-catch 块处理函数中抛出的异常时,可以使用 catch 子句捕获特定类型的异常。例如,要捕获 std::runtime_error 类型的异常,可以使用以下语法:

try {
  // 函数代码
} catch (const std::runtime_error& e) {
  // 处理 std::runtime_error 异常
}

实战案例:

假设有一个 read_file() 函数,它负责从文件中读取数据。如果文件不存在,函数会抛出一个 std::runtime_error 异常。我们可以使用 try-catch 块来处理此异常:

#include <iostream>
#include <fstream>

void read_file(const std::string& filename) {
  std::ifstream file(filename);
  if (!file.is_open()) {
    throw std::runtime_error("File not found");
  }
  
  // 读取文件内容
}

int main() {
  try {
    read_file("myfile.txt");
  } catch (const std::runtime_error& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
  return 0;
}

运行此程序,如果文件 "myfile.txt" 不存在,将打印以下错误消息:

Error: File not found