Home  >  Article  >  Backend Development  >  How to catch specific types of exceptions in C++ function exception handling?

How to catch specific types of exceptions in C++ function exception handling?

WBOY
WBOYOriginal
2024-04-15 22:09:02953browse

Methods to catch specific types of exceptions in C: use try-catch blocks. Specify the type of exception to be caught in the catch clause, such as catch (const std::runtime_error& e). In a practical case, the read_file() function handles the case where the file does not exist by throwing std::runtime_error, and uses a try-catch block to catch this exception and print the error message.

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

Catch specific types of exceptions in C function exception handling

In C, use try-catch When a block handles exceptions thrown in a function, you can use the catch clause to catch specific types of exceptions. For example, to catch exceptions of type std::runtime_error, you can use the following syntax:

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

Actual case:

Assume there is a read_file() Function, which is responsible for reading data from the file. If the file does not exist, the function throws a std::runtime_error exception. We can use a try-catch block to handle this exception:

#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;
}

Running this program, if the file "myfile.txt" does not exist, the following error message will be printed:

Error: File not found

The above is the detailed content of How to catch specific types of exceptions in C++ function exception handling?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn