您可以通过转换运算符的类型捕获异常吗? [英] Can you catch an exception by the type of a conversion operator?
问题描述
我不知道如何在一个简短的主题行中很好地说出这个问题,所以让我尝试一个更长的解释。假设我有这些异常类:
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
};
然后我可以这样做,并触发catch块吗?
Can I then do this, and have it trigger the catch block?
try
{
throw ExceptionTypeB();
}
catch (ExceptionTypeA& a)
{
// will this be triggered?
}
我要猜测它不会,这是不幸的,但是我以为我会问,因为我没有在网上或在SO上找到任何信息。是的,我意识到我可以在我的编译器中运行程序,看看会发生什么,但是不能告诉我这个行为的标准是什么,就是我的编译器实现的(我不相信它) / p>
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).
推荐答案
你不能。标准在 15.3 / 3
:
处理程序是一个异常对象的匹配如果
A handler is a match for an exception object of type E if
- 处理程序的类型为$ code> cv T 或
cv T&
和E和T是相同的类型(忽略顶级cv-
限定词),或者 - 处理程序是
cv T
或cv T&
,T是E的明确的公共基类,或 - 处理程序的类型为
cv1 T * cv2
,E是可以转换为处理程序类型的指针类型
通过
- 不涉及到私有或受保护的指针的转换的标准指针转换(4.10)或
模糊类 - 资格转换
- The handler is of type
cv T
orcv T&
and E and T are the same type (ignoring the top-level cv- qualifiers), or - the handler is of type
cv T
orcv 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
您所需的场景不符合这些情况。
cv
表示const和/或volatile组合Your desired scenario matches none of these.
cv
means "const and/or volatile combination"这篇关于您可以通过转换运算符的类型捕获异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 不涉及到私有或受保护的指针的转换的标准指针转换(4.10)或