Catch Multiple Custom Exceptions? - C++

前端 未结 7 1473
我在风中等你
我在风中等你 2020-12-24 10:44

I\'m a student in my first C++ programming class, and I\'m working on a project where we have to create multiple custom exception classes, and then in one of our event handl

7条回答
  •  盖世英雄少女心
    2020-12-24 10:55

    If you have multiple exception types, and assuming there's a hierarchy of exceptions (and all derived publicly from some subclass of std::exception,) start from the most specific and continue to more general:

    try
    {
        // throws something
    }
    catch ( const MostSpecificException& e )
    {
        // handle custom exception
    }
    catch ( const LessSpecificException& e )
    {
        // handle custom exception
    }
    catch ( const std::exception& e )
    {
        // standard exceptions
    }
    catch ( ... )
    {
        // everything else
    }
    

    On the other hand, if you are interested in just the error message - throw same exception, say std::runtime_error with different messages, and then catch that:

    try
    {
        // code throws some subclass of std::exception
    }
    catch ( const std::exception& e )
    {
        std::cerr << "ERROR: " << e.what() << std::endl;
    }
    

    Also remember - throw by value, catch by [const] reference.

提交回复
热议问题