C++异常相关。
要点
C++抛出异常的几种方式
- throw std::bad_cast();
- throw; ——只能用在catch(){}的语句块中,把已经捕获到的这个异常再次抛出,让其他地方继续处理
catch的方法
- catch (std::bad_cast& e): 捕获特定类型的异常
- catch (…):捕获所有的异常
如果程序中异常没有被捕获,则main()会调用terminate。
bad_cast的实现差异
bad_cast的实现不一样。gcc是无参数构造函数(缺省构造函数),而vs2013是包含一个const char*的构造函数。
Mingw&gcc的实现
/**
* @brief Thrown during incorrect typecasting.
* @ingroup exceptions
*
* If you attempt an invalid @c dynamic_cast expression, an instance of
* this class (or something derived from this class) is thrown. */
class bad_cast : public exception
{
public:
bad_cast() _GLIBCXX_USE_NOEXCEPT { }
// This declaration is not useless:
// http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118
virtual ~bad_cast() _GLIBCXX_USE_NOEXCEPT;
// See comment in eh_exception.cc.
virtual const char* what() const _GLIBCXX_USE_NOEXCEPT;
};
VS2013的实现
class _CRTIMP_PURE bad_cast : public exception {
public:
#ifdef _M_CEE_PURE
__CLR_OR_THIS_CALL bad_cast(const char * _Message = "bad cast")
: exception(_Message)
{}
__CLR_OR_THIS_CALL bad_cast(const bad_cast &_That)
: exception(_That)
{}
virtual __CLR_OR_THIS_CALL ~bad_cast() _NOEXCEPT
{}
#if defined(_CRTBLD) && defined(CRTDLL)
private:
// This is aliased to public:bad_cast(const char * const &) to provide
// the old, non-conformant constructor.
__CLR_OR_THIS_CALL bad_cast(const char * const * _Message)
: exception((const char *)_Message)
{ }
#endif /* _CRTBLD && CRTDLL */
#else /* _M_CEE_PURE */
__CLR_OR_THIS_CALL bad_cast(const char * _Message = "bad cast");
__CLR_OR_THIS_CALL bad_cast(const bad_cast &);
virtual __CLR_OR_THIS_CALL ~bad_cast() _NOEXCEPT;
#if defined(_CRTBLD) && defined(CRTDLL)
private:
// This is aliased to public:bad_cast(const char * const &) to provide
// the old, non-conformant constructor.
__CLR_OR_THIS_CALL bad_cast(const char * const * _Message);
#endif /* _CRTBLD && CRTDLL */
#endif /* _M_CEE_PURE */
};
头文件的位置
- Windows+MinGW:在mingw安装目录下搜索typeinfo
- Linux:在/usr/include/目录下搜索typeinfo