+ 2
Can I use try/catch without throw? What does throw 0 mean?
5 Antworten
+ 1
Hi Shola, yes you can use try / catch without a throw. Nevertheless, as try / catch only makes sense if an exception can be thrown, this code would not make much sense.
Throw 0 throws the integer 0. This seems weird, I know, because most thrown instances are instances of the class std::exception. Honestly, I can't think of a good reason to throw just integers... So I guess it's still there for backward compatibility.
+ 1
Throwing an integer is useful when you write your own exception class.
If you write your own exception class, you can execute different code blocks based on what integer you throw.
Ex. If(condition == 1)
Execute code block
Else if (condition == 2)
Execute different block
..........
Different parts of your code can throw different numbers. But that's just one way of doing exceptions.
0
0
0
@cody: You could just add a field to the exception, if data has to be transported. Apart from that there's a reason why different types of exceptions are used. The catch block filters on type, not on value. Therefore, the compiler takes care what code is executed depending on the type thrown. Throwing integers and then having to check on their value is problematic as a programmer can forget to check at all or just a case or two. This is why exceptions where introduced: to prevent sloppy error handling via error codes as error codes had been in around for many years before exceptions where conceived.
To be honest, I forget to check on error codes pretty much regularly. :-)
0
yes bro