I am building my first Java library. The code uses lots of IO methods, so as you can imagine there are lots of exceptions to be caught. But I’m wondering, should I throw the exceptions? I mean surely it’s the application writer’s job to catch the exceptions. Because even if I catch them, I don’t really know what the application would like to do in the event of this occurrence.
Should I throw IOExceptions etc, or should I catch them in the library code?
You should handle exceptions only if you can – i.e. if your library has sufficient knowledge on how the exception should be dealt with.
Here’s an example when you should handle an exception:
Here’s an example where you should not handle an exception
If you are going to throw an exception to the user, it is often good practice to catch and re-throw the exception – this enables you to wrap it in your own custom exception class and potentially add extra messages / details etc.
In general remember that if you want to write a good software component then it should have fail-fast behaviour. If in doubt, you should fail and let the user know (via an exception) rather than attempt to continue on an unsound basis.