Is there any advantages to throw other thing that a std::exception( or derivatives types)

后端 未结 5 1026
广开言路
广开言路 2021-01-21 02:25

Is there any advantages or uses cases to throw other thing that a std::exception( or a derivatives types).

For example throw 1; or throw \"error\";

5条回答
  •  耶瑟儿~
    2021-01-21 03:18

    From reference material about std::exception:

    std::exception

    All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type by reference.

    By throwing anything else, for example NuclearPlantException, you could handle your exceptions and the ones from the standard library separately. The standard library could throw std::invalid_argument or std::bad_alloc (subtypes of std::exception) and you could throw LossOfCoolant (a subtype of NuclearPlantException).

    So there is at least one advantage: separating standard library exceptions from your exceptions. Because you don't throw std::bad_alloc if there's enough available space for your uranium, then any exception has a clear origin, potentially making testing and debugging easier.


    Note: For more in-depth discussion see the question Should I inherit from std::exception?.

提交回复
热议问题