Home > Backend Development > C++ > body text

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

WBOY
Release: 2024-04-15 22:09:02
Original
945 people have browsed it

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 异常
}
Copy after login

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;
}
Copy after login

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

Error: File not found
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!