gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
how to do same action for two different exceptions caught in try/catch in c++11
- User
how to do same action for two different exceptions caught in try/catch in c++11
- Assistant
In C++11, you can use a single catch block to handle multiple exceptions by using a base class for those exceptions. Here's an example:
try { // code that may throw exceptions } catch (const std::exception& e) { // handle exceptions of base class std::exception std::cerr << "Exception caught: " << e.what() << std::endl; } catch (const std::runtime_error& e) { // handle exceptions of derived class std::runtime_error std::cerr << "Runtime error caught: " << e.what() << std::endl; } catch (const std::logic_error& e) { // handle exceptions of derived class std::logic_error std::cerr << "Logic error caught: " << e.what() << std::endl; }In this example, all exceptions thrown by the code that derive from
std::exceptionwill be caught by the first catch block. Then, exceptions that derive fromstd::runtime_errorwill be caught by the second catch block, and exceptions that derive fromstd::logic_errorwill be caught by the third catch block.This allows you to handle different types of exceptions with similar behavior in a more concise way.