c++ - 从 std::runtime_error 私有(private)继承的类未被捕获为 std::exception

标签 c++ exception try-catch

都在这个例子里

class MyException: std::runtime_error // note, there is no public keyword in inheritance
{
public:
   MyException(const std::string & x)
      : std::runtime_error(x)
   {}
};


int main( )
{
   try
   {
      throw MyException("foo");
   }
   catch (std::exception & e )
   {
      std::cout << "catched std exception: " << e.what() << std::endl;
   }
   catch (...)
   {
      std::cout << "catched ... " << std::endl;
   }
}

它在标准输出字符串“catched ...”上写入。但是,如果我将继承更改为 public 作为 class MyException : public std::runtime_error,它会按预期工作(对我而言)并写入“catched std exception: foo

c++ 标准的哪一部分要求这样的行为?为什么?在什么情况下这种行为可能有用?

最佳答案

有道理,符合重载决议的规则。在 MyException 之外,您的类不是 std::exception。您应该将私有(private)继承视为一个实现细节(具有非常高的耦合度。)

15.3处理异常中:

A handler is a match for an exception object of type E if

— The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or

— the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or

— the handler is of type cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler by either or both of - a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes — a qualification conversion

— the handler is a pointer or pointer to member type and E is std::nullptr_t.

(强调我的)

关于c++ - 从 std::runtime_error 私有(private)继承的类未被捕获为 std::exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520673/

相关文章:

unit-testing - 佩斯特可以 mock 一个异常(exception)吗?

java - 是否应该最小化 try catch 中的代码或管理它们的任何实践?

c++ - 为什么在调用这个列表时需要 "&"?

C++ 数组,数组转换不起作用

C++ 更快的字符数组比较

c++ - 防止 gcc/libstdc++ 在从 throw() 方法抛出时调用终止

c# - 调用 C++ dll 时出现 System.AccessViolationException

c++ - 按返回类型重载模板

java - 未知 "NumberFormatting"问题

java - 使用 try-catch java