简体   繁体   中英

C++ catch(std::exception & e ) vs. catch(...)

I know the difference in handling of both of these catches, but what does it take for the ellipse to catch something the std::exception catch wouldn't catch?

For example:

try
{
    throw std::runtime("runtime error!");
}
catch(const std::exception& e)
{
    std::cout << "Exception: " << e;
}
catch(...)
{
    std::cout << "How did I get here?";
    throw;
}

I've seen examples of code that use both of these in conjunction, but I've not seen a reason you would do both.

catch(const std::exception& e)

Will catch std exceptions only.

catch(...)

Will catch everything there after.

You can handle integers and other types ( http://www.cplusplus.com/doc/tutorial/exceptions/ )

For example:

catch(int e)

While it's definitely a good idea to do so, you don't have to derive your custom exceptions from std::exception . C++ allows you to throw practically any object type.

So throw 1; will not be handled by your first handler, for example. And neither will...

class MyCustomException { // Doesn't derive
 ///
};

... if it was thrown.

You probably meant:

throw std::runtime_error("runtime error!"); // not std::runtime

The std::runtime_error is derived from the std::exception so your first catch block is fired up as it catches exceptions of type std::exception . And there you probably meant:

std::cout << "Exception: " << e.what(); // not e

If you threw anything else other than the std::run_time or std::exception and its derivatives, the second catch block would be triggered. Useful reading from the C++ FAQ: What should I throw?

As written, the throw statement throws an object whose type is derived from std::exception , so it's caught by the first catch clause. If you change the throw to throw 3; the exception will be caught by the second catch clause, not the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM