例外をキャッチしてメイン関数で処理した後、プログラムをシャットダウンする最良の方法は何ですか?エラー時にプログラムを終了させる最も良い方法は何ですか?
- リターン
- にSystem.exit(...)
- 再スロー例外
- 実行時例外に他の
何か
を投げるラッパー- としてカスタム例外を投げます
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"); return; } List<List<String>> files = new ArrayList<>(); for (String s : args) { try { files.add(Utilities.readFile(s)); } catch (NoSuchFileException e) { System.out.printf("File %s does not exist%n", e.getMessage()); System.exit(-1); } catch (NoRegularFileException e) { System.out.printf("File %s is not a regular file%n", e.getMessage()); throw e; } catch (AccessDeniedException e) { System.out.printf( "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) { e.printStackTrace(); }
編集:プログラムの中にメインの終わりの前にいくつかの他のコードがあることを明らかにしておく必要があります。
「最適」を定義する方法によって異なります。 – Kayaman
catchがmainメソッドの最後の部分である場合、catchは実行され、mainはとにかく終了します。エラー報告をしたいのであれば、常にcatchブロックにログインすることができます。 –
例外をスローするか、エラーメッセージを出力するのではなく、例外をログに記録するほうがよいでしょう。また、エラーメッセージ( 'System.err.println(" Your message ");')を出力するときに 'Error Stream'を使うべきです。これらとは別に、 'System.exit(1);でプログラムを終了すると、その作業を行うべきです。 – Lefteris008