问题
I created a function that throws an exception, but under some circumstances I want it to simply ignore this exception.
I wrote my code like this, but it's not quite elegant:
try {
myFunction();
} catch (...) {}
Does C++ another way to write this?
回答1:
No, there isn't.
you can follow what the standard does in this case which is to overload the function twice, once with std::nothrow_t and once without. use the later to wrap the first
std::error_code my_function(std::nothrow_t) noexcept;
void my_function(); //throws
回答2:
No, that is how you would write it.
It's not bad in and of itself, though if you find that your code is becoming ugly due to the number of times you're employing this construct, that may be a signal that you're employing it too much.
I find myself ignoring exceptions occasionally, but if it's the "norm" for you then something may be wrong with your design.
回答3:
You can write inhibiting wrapper template method like this:
#include <utility>
template< typename Callable, typename... Arguments > void
Ingnore_Exceptions(Callable && method, Arguments && ... arguments) noexcept
{
try
{
method(::std::forward< Arguments >(arguments)...);
}
catch(...)
{
// Do nothing.
}
}
void
May_Throw(int, char const *)
{
throw(-1);
}
int
main(int, char**)
{
Ingnore_Exceptions(May_Throw, 42, "whatever");
return(0);
}
回答4:
The right way to do it would be
try
{
MyFunction () ;
}
catch (ExpectedExceptionType &e)
{
// Do nothing
}
回答5:
We can,t ignore the exception directly. If u want ignore the exception
try
{
myFunction();
}
catch(Exception)
{}
It will catch all the exception and doe not do anything due to empty catch block and your condition of ignore is satisfied.
来源:https://stackoverflow.com/questions/43437963/does-c-have-a-way-to-ignore-an-exception-from-a-function