How to construct a or exception without throwing?

前端 未结 4 942
自闭症患者
自闭症患者 2020-12-19 09:40

Exceptions defined in (e.g. std::logic_error, std::runtime_error and their subclasses such as std::system_erro

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 10:20

    Your problem is true only if you are trying to use built-in exception types. Although what some other answers in this thread say, there is a difference between throwing and failing, and there is a difference between throwing different types of exceptions.

    How can I say that? Because this is how the exceptions mechanism is built for.

    Failing to allocate on the stack provide no easy recovery while failing to allocate on the heap just throws. There is a difference because there is a way to recover from heap failure. In the same way, one can catch different exceptions because one might deal differently with them. There is such a mechanism because recovery might be very different.

    Moreover, while bad_alloc might not be very common on most platforms and applications, it is something that one should take care of, especially in those cases where memory is small and/or application requires lots of it. And yes, recovery from bad_alloc might sometimes be very different than recovery from other issues, like database errors or connection issues. It is true, though, that if you get the bad_alloc when trying to allocate only enough room for a very short message, you are on a deep problem, but still there might be recovery option (e.g.: If you hold lots of data for caching purpose only, you might release them).

    Nevertheless, the solution is quite simple - it is not a coincidence that the what() function of std::exception is virtual, and it returns the simplest type - const char *. You can inherit any exception you want directly from std::exception, and implement it in a way that does not allocate on the heap. For example, have the message as a static member of your class (possibly with some placeholders for values) or just provide it as a string literal. That way you can make sure that no new allocation is to be done upon throwing.

提交回复
热议问题