Java – Function returning true/false vs. void when succeeding and throwing an exception when failing

api-designarchitectural-patternsexceptionsfunctionsjava

I'm building an API, a function that uploads a file. This function will return nothing/void if the file was uploaded correctly and throws an exception when there was some problem.

Why an exception and not just false? Because inside an exception I can specify the reason of failure (no connection, missing filename, wrong password, missing file description, etc.). I wanted to build a custom exception (with some enum to help the API user to handle all the errors).

Is this a good practice or is it better returning an object (with a boolean inside, an optional error message and the enum for errors)?

Best Answer

Throwing an exception is simply an additional way of making a method return a value. The caller can check for a return value just as easily as catch an exception and check that. Therefore, deciding between throw and return requires other criteria.

Throwing exceptions should often be avoided if it endangers the efficiency of your program (constructing an exception object and unwinding the call stack is much more work for the computer than just pushing a value onto it). But if the purpose of your method is to upload a file, then the bottleneck is always going to be the network and file system I/O, so it's pointless to optimize the return method.

It's also a bad idea to throw exceptions for what should be a simple control flow (e.g. when a search succeeds by finding its value), because that violates the expectations of API users. But a method failing to fulfill its purpose is an exceptional case (or at least it should be), so I see no reason for not throwing an exception. And if you do that, you might just as well make it a custom, more informative exception (but it's a good idea to make it a subclass of a standard, more general exception like IOException).

Related Topic