引发同一类型的多个异常

Throwing multiple exceptions of the same type

本文关键字:异常 类型      更新时间:2023-10-16

所以我有一个程序,有两个例外。在这两种情况下,我都想抛出一个可以在 main 函数中捕获并在错误消息中使用的字符串。但是,据我对他们的了解

    try {
     ...
    } catch(string msg) {
     cerr << "..." << msg << "..." << endl;
    } catch (string msg2) {
     cerr << "..." << msg2 << "..." << endl;
    }

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

我看到两个用例:

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(); }
};

并抓住那些:

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

注意:对于自定义异常来说,这是一个简单但不是最佳设计,因为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";
}

注意:如果唯一需要的行为是不同的输出,则可以在没有自己类型的情况下模拟案例 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";
}

使用 std::runtime_error 它有一个接受字符串的构造函数。因此,在抛出时传递不同的值。

 throw runtime_error( "msg1");
 ...
 throw runtime_error("msg2");

然后当你捕获时,只需在对象中打印消息

 ...
 catch( exception& e ){
     cout << e.what() << endl;
 }

第一:你的编译器应该为此发出警告,因为第二个catch永远不会被执行,因为它们具有确切的签名。此外,你不能在第一个异常处于活动状态时抛出第二个异常(在堆栈展开期间抛出的异常尚未进入catch块),否则,运行时将终止你的程序。

其次:更喜欢通过引用来捕获您的异常

第三:希望你的异常对象落在std::exception的继承树中。

最后:你到底想做什么?