What throw statement throws if i do not tell what type of object is to be thrown in c++?

前端 未结 2 1058
天命终不由人
天命终不由人 2021-01-18 15:39

The following code terminates abnormally as no object is explicitly thrown. What is thrown by throw statement in the following code?

int main()
{
  try{
  co         


        
2条回答
  •  伪装坚强ぢ
    2021-01-18 15:43

    throw without an argument should only be used inside a catch statement, to rethrow the caught exception object. You code tries to use it outside the catch statement - instead you should pick a type to throw, if in doubt it's not unreasonable to start with std::runtime_error. For more options, see here. You can also throw your own types, but it's usually a good idea to derive them from one of the Standard-library provided types so client code has a better chance at specifying appropriate handling for all logically similar errors, rather than having to catch and handle them separately and being constantly updated for each new possible error.

    FWIW, the Standard says in 15.1/9:

    If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate().

    So very explicitly, the answer to "What is thrown..." is that no throwing is done, and std::terminate is called instead.

提交回复
热议问题