如果我抛出一个字符串文字,我应该捕获什么类型? [英] What type should I catch if I throw a string literal?
问题描述
我正在使用 Linux 下的 g++ 在 C++ 中编写一个非常简单的应用程序,并且我试图抛出一些原始字符串作为异常(是的,我知道,这不是一个好习惯).
I am writing a pretty simple application in C++ using g++ under Linux and I am trying to throw some raw strings as exceptions (yes, I know, its not a good practise).
我有以下代码(简化):
I have the following code (simplified):
int main()
{
try
{
throw "not implemented";
}
catch(std::string &error)
{
cerr<<"Error: "<<error<<endl;
}
catch(char* error)
{
cerr<<"Error: "<<error<<endl;
}
catch(...)
{
cerr<<"Unknown error"<<endl;
}
}
我在控制台上得到 Unknow error
.但是,如果我将文字字符串静态转换为 std::string
或 char *
它会按预期打印 Error: not implemented
.我的问题是:如果我不想使用静态强制转换,我应该捕获什么类型?
And I get Unknow error
on the console. But if I static cast the literal string to either std::string
or char *
it prints Error: not implemented
as expected. My question is: so what is the type I should catch if I don't want to use static casts?
推荐答案
你需要用 char const*
而不是 char*
来捕捉它.std::string
和 char*
之类的东西都不会捕捉到它.
You need to catch it with char const*
instead of char*
. Neither anything like std::string
nor char*
will catch it.
Catching 对匹配的类型有限制性的规则.规范说(其中cv"表示const/volatile 组合"或两者都不是).
Catching has restricted rules with regard to what types it match. The spec says (where "cv" means "const/volatile combination" or neither of them).
如果
- 处理程序的类型为 cv T 或 cv T&并且 E 和 T 是同一类型(忽略顶级 cv 限定符),或者
- 处理程序的类型为 cv T 或 cv T&并且 T 是 E 的明确公共基类,或者
处理程序的类型为 cv1 T* cv2,E 是指针类型,可以通过其中一个或两个转换为处理程序的类型
- 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
- 标准指针转换 (4.10) 不涉及到指向私有或受保护或不明确类的指针的转换
- 资格转换
字符串字面量的类型为 char const[N]
,但抛出数组会使数组衰减,实际上会抛出指向其第一个元素的指针.因此,您无法通过 char*
捕获抛出的字符串文字,因为在匹配时,它需要将 char*
与 char const*
,这将丢弃一个 const(限定转换只允许 add const).仅在需要专门转换字符串文字时才考虑将字符串文字特殊转换为 char*
.
A string literal has type char const[N]
, but throwing an array will decay the array and actually throws a pointer to its first element. So you cannot catch a thrown string literal by a char*
, because at the time it matches, it needs to match the char*
to a char const*
, which would throw away a const (a qualification conversion is only allowed to add const). The special conversion of a string literal to char*
is only considered when you need to convert a string literal specifically.
这篇关于如果我抛出一个字符串文字,我应该捕获什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!