Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
On another note, I have found the grenade analogy to be great for explaining try-catch statements to people who don't get them.
-
@TheFlx Basically an Exception is a live grenade. You may have code which can "defuse" or handle that grenade. That's the code that goes into your "catch" statements, with the "try" statements marking out the points where your code has to watch out for incoming grenades.
Meanwhile, sometimes you may have a grenade that your code does not know how to defuse, or it may not be its job to do, or it may need additional information only available at a higher level to defuse it. So it simply "throws" the grenade at someone else who's looking for it (using "try") and catches it to defuse. Similarly you could catch a grenade and then throw it again because you look at it and realize it may not be appropriate to defuse at your level.
The grenade times out when it reaches the outermost point and no one catches it. At that point, it becomes an Unhandled Exception, or basically "explodes".
Hope this helps :) -
TheFlx5348y@Mindstormer619 thanks! I knew how exceptions work but that's a great way to explain it đź‘ŚCould've used it when I was trying to understand how these things worked haha
Related Rants
The legit mod of try-catch! :P
undefined
forever alone
try-catch-final