Ash*_*ish 0 c++ exception-handling
在Java中,Object类是所有类的基类.C++中是否还有这样的类?
我对这个问题的动机是:
try
{
if (something) throw int(a);
if (something) throw char(b);
if (something) throw float(c);
}
catch(...)
{
handle
}
Run Code Online (Sandbox Code Playgroud)
除此之外,还有其他方法可以使用单个catch块来处理所有这些异常吗?
C++中没有通用的基类.
异常类通常应该派生自std::exception,以便catch(const std::exception&)可以使用.
catch(...)捕获任何异常对象类型(包括基元类型).它可以在catch块内重新抛出throw;:
try
{
if (something) throw int(a);
if (something) throw char(b);
if (something) throw float(c);
}
catch(...)
{
if(stillFailed) throw; // throws the same exception again
}
Run Code Online (Sandbox Code Playgroud)
在块内部也可以使用std::exception_ptr表示抛出对象(未知类型)的对象.然后可以将其与其他对象进行相等性比较,或者使用其他函数重新进行比较.请参见http://en.cppreference.com/w/cpp/header/exception.无法直接访问异常对象,因为其类型未知.std::current_exception()catch(...)std::exception_ptrstd::rethrow_exception()
| 归档时间: |
|
| 查看次数: |
388 次 |
| 最近记录: |