kevinlelo kevinlelo - 1 year ago 48
Java Question

What's the best way to terminate a program on error?

What would you say is the best way to shut down a program after catching an exception and taking care of it in the main function?

  1. return

  2. System.exit(...)

  3. re-throw the exception

  4. throw a custom exception as a wrapper

  5. throw a runtime exception

  6. something else

    public static List<String> readFile(String file)
    throws NoSuchFileException, EOFException, IOException {
    Path p = Paths.get(file);
    if (!Files.exists(p)) {
    throw new NoSuchFileException(file);
    } else if (!Files.isRegularFile(p)) {
    throw new NoRegularFileException(file);
    } else if (!Files.isReadable(p)) {
    throw new AccessDeniedException(file);
    } else if (Files.size(p) == 0) {
    throw new EOFException(file);
    return Files.readAllLines(p);

    public static void main(String[] args) {
    try {
    if (args.length != 2) {
    System.out.println("The proper use is: java MyProgram file1.txt file2.txt");

    List<List<String>> files = new ArrayList<>();
    for (String s : args) {
    try {
    } catch (NoSuchFileException e) {
    System.out.printf("File %s does not exist%n", e.getMessage());
    } catch (NoRegularFileException e) {
    System.out.printf("File %s is not a regular file%n", e.getMessage());
    throw e;
    } catch (AccessDeniedException e) {
    "Access rights are insufficient to read file %s%n", e.getMessage()
    throw new ReadFileException(e);
    } catch (EOFException e) {
    System.out.printf("File %s is empty%n", e.getMessage());
    throw new RuntimeException(e);
    //some other code
    } catch (Exception e) {

Edit: I should have made it clear that there would be some other code in the program before the end of main, so I can't just let it finish.

Answer Source

If you want it to be clean (i.e. not display stacktrace to user), then throwing exceptions is out of the question (at least out of main). Then it's all about whether you want to return an exit code from the program if not.

If you want to return the exit code, you have to use System.exit(int errcode);. Otherwise you can just return (or let main exit normally).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download