现在的位置: 首页 > 综合 > 正文

C++能否抛出一个不是继承自std::exception的异常

2013年09月23日 ⁄ 综合 ⁄ 共 640字 ⁄ 字号 评论关闭

有这样一道面试题目:

 

try 
{
 
}
 
catch(const std::exception &e) 
{ 
}
 
catch(...)
 
{
 
 
//Is this block needed?
 
}
 

问第二个catch会捕获到异常吗?

 

答案是是的。。。你可以throw任何类型,不一定是std::exception的子类。可以throw一个整数,或者一个字符串。

http://stackoverflow.com/questions/908092/in-c-is-is-possible-to-throw-an-exception-that-will-not-be-caught-by-stdexce

 

yes. you can throw any type, not necessary types that inherit from std::exception.
you can write throw 1; to throw and int or throw "hello"; to throw a char*, both of which do not inherit from std::exception. this is however considered bad practice because the user of the class can't expect you to throw anything. If you don't want to inherit from std::exception what you usually do is create your own exception hierarchy.

抱歉!评论已关闭.