Can I use try/catch without throw? What does throw 0 mean? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can I use try/catch without throw? What does throw 0 mean?

8th Aug 2016, 12:01 PM
shola ola ibrahim
shola ola ibrahim - avatar
5 Answers
+ 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.
8th Aug 2016, 4:05 PM
Stefan
Stefan - avatar
+ 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.
10th Aug 2016, 8:46 AM
cody pickett
cody pickett - avatar
0
0
8th Aug 2016, 12:25 PM
Mr.Perfect
Mr.Perfect - avatar
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. :-)
10th Aug 2016, 9:05 AM
Stefan
Stefan - avatar
0
yes bro
13th Nov 2016, 2:57 PM
vikas singh