我想捕获一个异常并将其捆绑在我自己的异常中并向上抛出 [英] I want to catch an exception and bundle it within my own exception and throw upwards
问题描述
如果请求的资源不在缓存中,资源管理器将从装载机。如果加载程序失败,资源管理器会抛出一个我称之为LoadError的异常类。
我希望Loader类失败时抛出异常。如果需要,我可以要求他们继承自己的异常基类。
问题是,当引发LoadError时,我希望它包含关于为什么它失败的特定信息。但是我不知道Loader可能抛出什么异常。 (用户可能在他的资源管理器周围的catch块中)。
我可以抛出一些一般信息的LoadError,或者允许Loader出现特定的异常而不要碰它。但是我想捕获异常并将其绑定到我自己的LoadError异常中,或者在LoadingError中指向它。但是我不知道指针异常会持续多久(关注坏指针)。
我应该做哪三个? (和如何,对于第三个..)
谢谢
p>如何嵌套异常?
try {/ * ... * /}
catch 。)
{
throw MyException(发生错误,std :: current_exception());
}
只需制作一个合适的类来存储异常:
struct MyException:std :: exception
{
std :: string message;
std :: exception_ptr nested_exception;
MyException(std :: string m,std :: exception_ptr e)
:message(std :: move(m))
,nested_exception(std :: move ))
{}
// ...
};
当捕获异常时,捕获者可以重新抛出嵌套异常:
尝试{/ *加载资源* /}
catch(MyException& e)
{
log加载失败:+ e.what());
std :: rethrow_exception(e.nested_exception);
}
事实上,这整个逻辑已经由标准库通过 std :: throw_with_nested
。
I have a class that manages resources. It takes a Loader class that can retrieve the resource from a path. Loader is an abstract base class, so anyone could make a new loader.
If a resource is requested that is not in the cache, the resource manager will request it from the loader. If the loader fails, resource manager throws an exception class I made called LoadingError.
I want the Loader class to throw exceptions when it fails. I can require them to inherit from my own exception base class if necessary.
The problem is, when LoadingError is thrown, I want it to include specific information about why it failed. But I don't know exactly what exceptions may be thrown by the Loader. (The user might, in his catch blocks around the resource manager).
Either I can throw only LoadingError with some general information, or allow a specific exception from Loader come out and not touch it. But I would like to catch the exception and bundle it in my own LoadingError exception, or point to it in LoadingError . But I don't know how long the pointed-to exception will last (concerned about bad pointer).
Which of the three should I do? (And how, for the third one..)
Thanks
How about a nested exception?
try { /* ... */ }
catch (...)
{
throw MyException("An error occurred", std::current_exception());
}
Just make a suitable class that stores the exception:
struct MyException : std::exception
{
std::string message;
std::exception_ptr nested_exception;
MyException(std::string m, std::exception_ptr e)
: message(std::move(m))
, nested_exception(std::move(e))
{ }
// ...
};
When the exception is caught, the catcher can rethrow the nested exception:
try { /* load resource */ }
catch (MyException & e)
{
log("Resource loading failed: " + e.what());
std::rethrow_exception(e.nested_exception);
}
In fact, this entire logic is already provided by the standard library via std::throw_with_nested
.
这篇关于我想捕获一个异常并将其捆绑在我自己的异常中并向上抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!