Hacker News new | ask | show | jobs
by hi41 2584 days ago
I have c programming experience but not java. I would greatly appreciate if you can tell me the where to catch an exception. When there are nested method calls I can’t tell where to handle it correctly - should I handle it in the top most function or the one where the current method was called from? Can you point me to some resources so that I can understand the correct way of handling exceptions.
2 comments

As the paper and the article say, what matters is not the technical aspect of where to handle an exception, but to give some serious thought to what should be done when it occurs (as opposed to just logging it). Serious problems happen when people don't pay enough attention to that.
You should handle it in the most immediate context which can do something productive with it- if there's nothing you can do but swallow it, you should probably let it continue to pass up the stack. If you can handle it and log a warning and return something else, you should handle it there.

For example, if you're writing an HTTP handler for an API, you should catch any exceptions at that point in your handler and return a 500 with an appropriate response to the client, since returning 500 is something productive we can do (vs letting it pass and crashing the server).

Thank you for offering pointers to effective usage of exceptions.