Suppose I have a controller that loads a file and hands it over to the processing.
-
Should I handle the exception in the file loader and return
Null
if something is wrong, or should I throw the exception and handle it in the controller? -
Without the file the rest of the program can´t work. Where should I handle a exception that shuts down the program properly?
I want to shut down an Android application properly.
In layman’s words:
- You should not return null.
- The exception should be handled in the top-most layer.
- The program should not terminate, but give feedback to the user, unless it is a Unix style command line program where it’s ok to terminate after showing an error message.
- By definition no exception is fatal and each one can be handled.
- Errors are fatal and cannot be recovered from.
- Exceptions and errors are not the same.
5
Exceptions should go up until they reach the layer where you need to take care of them (i.e. catch them and act accordingly).
In your example, it seems you need to load a file; if the file is not found or is corrupt, you want to close the application. In this case, it seems that you should catch the exception at the outermost layer (loader -> controller -> … -> entry point — catch here), present an error message to the user, and quit. Catching the exception anywhere else will only make your code more convoluted and difficult.
This makes sense if the file is not something that depends on the user and the user cannot do anything to fix the file if it is wrong or missing.
On the other hand, if the file is one that is chosen by the user (or can be), you should show an error message to the user, and then give the opportunity of finding the right file instead of quitting.