你可以通过转换操作符的类型捕获异常吗? [英] Can you catch an exception by the type of a conversion operator?

查看:138
本文介绍了你可以通过转换操作符的类型捕获异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在短主题行中很好地说出问题,所以让我尝试更长的解释。假设我有这些异常类:

  class ExceptionTypeA:public std :: runtime_error 
{
// stuff
};

class ExceptionTypeB:public std :: runtime_error
{
// stuff

操作符ExceptionTypeA()const; // conversion operator to ExceptionTypeA
};我可以这样做,并且它触发catch块吗?







$ b < b

  try 
{
throw ExceptionTypeB();
}
catch(ExceptionTypeA& a)
{
//会被触发吗?
}



我会猜测不会,这是不幸的,但我想我会问,因为我在网上或在SO上找不到任何信息。是的,我意识到我可以在我的编译器运行程序,看看会发生什么,但不会告诉我什么标准说这个行为,只是我的编译器实现(我不相信它)。

解决方案

你不能。标准版 15.3 / 3


处理程序与异常对象如果




  • 处理程序类型为 cv T cv T& 和E和T是相同的类型(忽略顶级cv-
    限定符),或

  • cv T cv T& 类型,T是E的明确公共基类,或

  • 处理程序类型为 cv1 T * cv2 ,E是可以转换为处理程序类型的指针类型


    • 一个标准指针转换(4.10),不涉及转换为private或protected或
      模糊类的指针

    • 资格转换



期望场景与这些都不匹配。 cv 表示const和/或易失性组合


I don't know how to phrase the question very well in a short subject line, so let me try a longer explanation. Suppose I have these exception classes:

class ExceptionTypeA : public std::runtime_error
{
    // stuff
};

class ExceptionTypeB : public std::runtime_error
{
    // stuff

    operator ExceptionTypeA() const; // conversion operator to ExceptionTypeA
};

Can I then do this, and have it trigger the catch block?

try
{
    throw ExceptionTypeB();
}
catch (ExceptionTypeA& a)
{
    // will this be triggered?
}

I'm going to guess that it will not, which is unfortunate, but I thought I'd ask, since I couldn't find any info on it on the net or on SO. And yes, I realize I could just run the program in my compiler and see what happens, but that wouldn't tell me what the standard says about this behavior, just what my compiler implements (and I don't trust it).

解决方案

You cannot. Standardese at 15.3/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

Your desired scenario matches none of these. cv means "const and/or volatile combination"

这篇关于你可以通过转换操作符的类型捕获异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆