在C++中,throw;当在catch块内执行时,重新抛出块外的当前捕获的异常.
在这个答案中,当经常使用复杂的异常处理时,会提出异常调度程序的概念作为减少代码重复的解决方案:
try {
CodeThatMightThrow();
} catch(...) {
ExceptionHandler();
}
void ExceptionHandler()
{
try {
throw;
} catch( FileException* e ) {
//do handling with some complex logic
delete e;
} catch( GenericException* e ) {
//do handling with other complex logic
delete e;
}
}
Run Code Online (Sandbox Code Playgroud)
抛出指针或值没有任何区别,所以这是不可能的.
如果不是从catch块调用ExceptionHandler()会发生什么?
我用VC7尝试了这段代码:
int main( int, char** )
{
try {
throw;
} catch( ... ) {
MessageBox( 0, "", "", 0 );
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,它使调试器指示第一次机会异常,然后立即指示未处理的异常.如果我在调试器外运行此代码,程序崩溃的方式与调用abort()的方式相同.
这种情况的预期行为是什么?
可能重复:
捕获异常后确定异常类型?
关注这个问题,我想在catch(...)块中打印出当前的异常- 只是为了记录.有一个答案说没有标准的方法可以做到这一点,但我不喜欢不回答:-)
current_exception()是在网络上的各个地方提到的功能,但显然不是很好的支持.有什么想法吗?毕竟,即使C也有错误.
因为它可以被重新抛出(使用简单的**throw*),异常对象必须以某种方式可用.
我正在使用MSVS 9.0.
编辑:结论似乎是这是不可能的.
我正在编写C++ Primer,第5版,作者提供了一个示例,使用shared_ptrs来管理可能泄漏内存的旧库中的资源,以防止它们这样做.我决定创建一个测试来查看它是如何工作的,但是在抛出异常并且(故意)没有捕获之后我的自定义删除器不会被调用:
#include <iostream>
#include <memory>
#include <string>
struct Connection {};
Connection* Connect(std::string host)
{
std::cout << "Connecting to " << host << std::endl;
return new Connection;
}
void Disconnect(Connection* connection)
{
std::cout << "Disconnected" << std::endl;
delete connection;
}
void EndConnection(Connection* connection)
{
std::cerr << "Calling disconnect." << std::endl << std::flush;
Disconnect(connection);
}
void AttemptLeak()
{
Connection* c = Connect("www.google.co.uk");
std::shared_ptr<Connection> connection(c, EndConnection);
// Intentionally let the exception bubble up.
throw;
}
int main()
{
AttemptLeak();
return …Run Code Online (Sandbox Code Playgroud)