卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79534本站已运行4414

C++ 中函数参数的异常处理机制是如何工作的?

在 c++++ 中可以使用异常处理机制处理函数参数中的异常情况:当函数内出现错误时,可以使用 throw 语句抛出一个异常对象。函数自身和调用它的函数都可以通过 try 和 catch 块捕获异常。实战案例:在 getfilepath() 函数中,当输入的文件路径无效时抛出一个异常。

C++ 中函数参数的异常处理机制是如何工作的?

C++ 中函数参数的异常处理机制

在 C++ 中,函数参数可以通过异常处理机制来处理异常情况。异常处理机制允许在发生错误时将控制权转移到代码的其他部分。

异常抛出

立即学习“C++免费学习笔记(深入)”;

当函数内部发生错误时,可以使用 throw 语句抛出一个异常对象。异常对象是一种特殊的类型,它包含有关错误的附加信息。

void myFunction(int num) {
  if (num < 0) {
    throw std::invalid_argument("num must be non-negative");
  }
  // ...
}

异常捕获

函数自身和调用它的函数都可以通过 try 和 catch 块来捕获异常。

void myFunction(int num) {
  try {
    if (num < 0) {
      throw std::invalid_argument("num must be non-negative");
    }
    // ...
  } catch (std::invalid_argument& e) {
    // 异常处理代码
  }
}

实战案例

考虑一个函数 getFilePath(), 它从用户输入中获取文件路径。如果输入的路径无效,则函数应抛出异常。

#include <iostream>
#include <filesystem>

std::string getFilePath() {
  try {
    std::string path;
    std::cout << "Enter file path: ";
    std::getline(std::cin, path);

    if (!std::filesystem::exists(path)) {
      throw std::invalid_argument("File not found at " + path);
    }
    return path;
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
    throw;  // 将异常重新抛出
  }
}

int main() {
  std::string filePath;
  try {
    filePath = getFilePath();
    // ... 使用文件路径
  } catch (std::invalid_argument& e) {
    std::cout << "Error: " << e.what() << std::endl;
  }

  return 0;
}
卓越飞翔博客
上一篇: PHP 函数优化中循环的处理技巧和注意事项
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏