james_dean
james_dean

Reputation: 1517

Where to deal with a file exception?

I've been working on a console based Inventory program as part of my course, and now I need to store and parse the data in files. So, I have stored all of my data in csv files and have a dedicated 'file' with a generic loadFile() method.

If the Inventory or config file cannot be found, it doesn't really make sense for the program to continue as everything else depends on them.

As such, I'm simply catching the file within the loadFile() method and printing a statement to the user and then using System.exit() to close.

Is this good practice? Is there a more elegant way of terminating the program after the correct error message has been printed?

Upvotes: 1

Views: 68

Answers (3)

jjm
jjm

Reputation: 6198

No.

The purpose of exceptions is to indicate exceptional conditions. Since your program won't work without its input files, System.exit() is exactly the right thing to do.

Upvotes: 3

Leesrus
Leesrus

Reputation: 1115

In this sort of situation I usually prefer to throw an unchecked exception from the loadFile() method as the program cannot recover from this situation, for example a RuntimeException or an IllegalStateException. This exception will cause the application to exit unless you decide to catch it and handle it.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

I would handle it only when you can do something useful. If you want to stop the program the simplest this to do is have your main throw IOException.

public static void main(String... args) throws IOException {

Upvotes: 1

Related Questions