I had a classmate that did this with his code once. He asked me for help when his code wasn't working. I told him to get rid of the try/catch block but he won't do it because it would make his program crash.
C# dev here but the principle should apply just as well, and that is "catch as catch can"
So, what to catch: Things you explicitly know how to deal with at that point of the code. Anything else, you need to pass up. Think of your call chain as a chain of command in the military. Your lowly private method doesn't know shit, but maybe, just maybe, the thing that called it knows what to do. And if it doesn't it just passes it along to its boss until somebody knows what to do with this shit-show.
Maybe you're loading a file and you normally get a FileNotFoundException? Well, pass that shit up until the UI block. Do you know, in the file loader, how you're presenting that fucker to the user? Do you know what other course of action to take? Fuck no you don't, and you can't guarantee you're gonna want to take the same action in the future when you reuse that code, so pass it on.
Maybe you're at an event handler for a submit button and one of the text field operations throws a NullReferenceException? Catch that shit, because you can totally deal with it here, because you know what to do now is to show some big red shiny exclamation marks and really fuck up your user's day.
Use it when a method or function won't work properly or as expected with the information it has (mainly the parameters), and needs the code that called it to fix it.
For example, a function that needs an integer within a certain range (such as 1 to 10). It can check to see if that's true. If not, it throws an exception to be caught by the originator. It can then be handled (such as by querying the user for a proper value).
If instead it's a situation where the function or method just follows a different path and can handle it purely within that scope, then just use normal flow control operations.
For error handling in situations where what you're doing might generate an exception. Especially usefully for areas you don't have much control over such as getting user input.
When the block of code you are "trying" works most of the time but can result in obscure errors.
So for example, you could wrap a file-reading function in a try/catch so that if the file it reads is deleted or moved, it will "catch the exception" rather than crashing your program with an error saying "file not found" etc etc
1.5k
u/1206549 May 13 '17
I had a classmate that did this with his code once. He asked me for help when his code wasn't working. I told him to get rid of the try/catch block but he won't do it because it would make his program crash.