2016-05-09 7 views
-2

例外をキャッチしてメイン関数で処理した後、プログラムをシャットダウンする最良の方法は何ですか?エラー時にプログラムを終了させる最も良い方法は何ですか?

  1. リターン
  2. にSystem.exit(...)
  3. 再スロー例外
  4. 実行時例外に他の
  5. 何か

    を投げるラッパー
  6. としてカスタム例外を投げます
    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(); 
        } 
    

編集:プログラムの中にメインの終わりの前にいくつかの他のコードがあることを明らかにしておく必要があります。

+1

「最適」を定義する方法によって異なります。 – Kayaman

+0

catchがmainメソッドの最後の部分である場合、catchは実行され、mainはとにかく終了します。エラー報告をしたいのであれば、常にcatchブロックにログインすることができます。 –

+0

例外をスローするか、エラーメッセージを出力するのではなく、例外をログに記録するほうがよいでしょう。また、エラーメッセージ( 'System.err.println(" Your message ");')を出力するときに 'Error Stream'を使うべきです。これらとは別に、 'System.exit(1);でプログラムを終了すると、その作業を行うべきです。 – Lefteris008

答えて

0

クリーンにする(つまり、ユーザーにスタックトレースを表示しない)場合は、例外をスローすることは問題ありません(少なくともメインから外れている)。次に、プログラムから終了コードを返すかどうかについては、すべてそれについてです。

終了コードを返信する場合は、System.exit(int errcode);を使用する必要があります。それ以外の場合は、返信することができます(またはmainを正常に終了させることができます)。

+0

それが返されます。 – kevinlelo

関連する問題