Hey StackOverflow Community,
Regarding throwing exceptions. Generally, when do I throw and exception, and when do I catch it?
Let’ say I come across these situation where I have to quit because of some problem that occurred and I can’t recover from it. Do I throw or do I catch?
I do this right now:
try {
// some code
}
catch (IOException e) {
logger.info("Failed to do something, and cannot continue" + e.getMessage(), e);
e.printStackTrace();
throw e;
}
Is this the right thing to do? Would it be more appropriate if I just threw the exception? Sorry, I’m a newbie at exceptions 🙂
You generally catch an exception in a method when you want your program to continue running. You throw an exception when you want a higher level method that is calling that method to handle the exception instead. For example, you might throw it all the way back to your Main method, which has a try..catch block (likely with different catch blocks for different exceptions) encapsulating all your method calls, and exceptions can be handled there (for example by ending the program).
Remember that throwing an exception will end the method immediately. This affects the flow of your code. If you might have an exception in the middle of the method, and the code below it can’t run if that exception happened, then you would need to either wrap the whole section in a try/catch block or throw an exception.
A general word of advice – printStackTrace() is bad. You can create better error output yourself (and you can include the stack trace as well with your output). Even better, use logging.
I recommend reading this introduction to exceptions and this article which covers good and bad exception patterns.