c++ - 抛出多个相同类型的异常

The*_*ner 0 c++ exception

所以我有一个有两个例外的程序。在这两种情况下,我都想抛出一个可以在主函数中捕获并在错误消息中使用的字符串。然而,据我所知

    try {
     ...
    } catch(string msg) {
     cerr << "..." << msg << "..." << endl;
    } catch (string msg2) {
     cerr << "..." << msg2 << "..." << endl;
    }
Run Code Online (Sandbox Code Playgroud)

不允许。有什么办法可以做到以上或类似的事情吗?谢谢

Pix*_*ist 5

我看到两个用例:

1. 您需要两种不同类型的错误。

添加派生自的异常类 std::exception

class MyException1 : public std::exception
{
  std::string message;
public:
  MyException1(std::string const &what_arg) : message(what_arg) {}
  MyException1(char const * what_arg) : message(what_arg) {}
  const char* what() const { return message.c_str(); }
};

class MyException2 : public std::exception
{
  std::string message;
public:
  MyException2(std::string const &what_arg) : message(what_arg) {}
  MyException2(char const * what_arg) : message(what_arg) {}
  const char* what() const { return message.c_str(); }
};
Run Code Online (Sandbox Code Playgroud)

并抓住那些:

try
{

  int a = 5;

  // do stuff

  if (a == 7)
  {
    throw MyException1("Error 1 occured in  because a == 7.");
  }
  else if (a == 5)
  {
    throw MyException1("Error 1 occured because a == 5.");
  }

  // do more stuff

  if (a == 22)
  {
    throw MyException2("Error 2 occured in  because a == 22.");
  }
  else if (a == 575)
  {
    throw MyException2("Error 2 occured because a == 575.");
  }

}
catch (MyException1 &ex)
{
  std::cout << "Exception 1: " << ex.what() << "\n";
}
catch (MyException2 &ex)
{
  std::cout << "Exception 2: " << ex.what() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

注意:对于自定义异常,这是一个简单但不是最佳的设计,因为它std::string可能会抛出并且您的程序将被终止。

2. 您需要两种不同的错误信息:

使用来自<stdexcept>标题的适当类型的异常:

try
{

  int a = 5;
  // do stuff
  if (a == 7)
  {
    throw std::runtime_error("Error 1 occured because a == 7.");
  }
  else if (a == 5)
  {
    throw std::runtime_error("Error 2 occured because a == 5.");
  }

}
catch (const std::exception &ex)
{
  std::cout << "Exception: " << ex.what() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

注意:如果唯一需要的行为是不同的输出,则可以在没有自己类型的情况2 中模拟情况1 的行为:

try
{

  int a = 5;
  // do stuff
  if (a == 7)
  {
    throw std::runtime_error("Exception 1: Error 1 occured in  because a == 7.");
  }
  else if (a == 5)
  {
    throw std::runtime_error("Exception 1: Error 1 occured because a == 5.");
  }
  // do more stuff
  if (a == 22)
  {
    throw std::runtime_error("Exception 2: Error 2 occured in  because a == 22.");
  }
  else if (a == 575)
  {
    throw std::runtime_error("Exception 2: Error 2 occured because a == 575.");
  }

}
catch (const std::exception &ex)
{
  std::cout << ex.what() << "\n";
}
Run Code Online (Sandbox Code Playgroud)