Catch Multiple Custom Exceptions? - C++

前端 未结 7 1477
我在风中等你
我在风中等你 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 11:03

    You should create a base exception class and have all of your specific exceptions derive from it:

    class BaseException { };
    class HourOutOfRangeException : public BaseException { };
    class MinuteOutOfRangeException : public BaseException { };
    

    You can then catch all of them in a single catch block:

    catch (const BaseException& e) { }
    

    If you want to be able to call GetMessage, you'll need to either:

    • place that logic into BaseException, or
    • make GetMessage a virtual member function in BaseException and override it in each of the derived exception classes.

    You might also consider having your exceptions derive from one of the standard library exceptions, like std::runtime_error and use the idiomatic what() member function instead of GetMessage().

提交回复
热议问题