What does: throw 0 do/mean? Is it “bad”?

前端 未结 3 902
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 18:25

Context

I came across some code, like this:

if( Some_Condition ) throw 0;

I googled a bit, and found a few other code snippets us

相关标签:
3条回答
  • 2021-01-11 19:00

    It is not special, you can thow int just as an exception class.

    It is considered a poor style, because an exception class can tell more about what actually happened.

    0 讨论(0)
  • 2021-01-11 19:03

    Generally throw can throw any type, any you need to catch it with this type or its base type.

    So technically it is legal code but...

    it is bad code: You should always derive your exceptions from std::exception or at least from some class that provides some useful information about error rather then plain number. But deriving from std::exception is the correct way because it allows to use topmost catch(std::exception const &e) and get at least some information about the error.

    0 讨论(0)
  • 2021-01-11 19:04

    It's an int. It is "bad", since throwing 0 makes the code unreadable, or hints someone is using exceptions as a value returning system. (It's basically the same problem as a magic number inside the code)

    NULL is defined as ((void *)0). If the compiler sees a 0 it means an int. It may be automatically casted to something else, but only if there's a reason (For example assignment to double). The line throw 0 does not give such a reason, so an int is thrown.

    0 讨论(0)
提交回复
热议问题