Java Exceptions

5162 ワード

1.よくあるエラー分類
一般的にerrorsは次のように分類されます.
  • user input errors
  • device errors or physical limitations
  • code errors

  • 2.常用エラー処理方式
    2.1 error code
    1つの一般的なエラー処理方法は、error codeを返し、calling methodがerror codeに基づいて異なる処理を行うことである.
    しかし、エラーコードとエラーコードと同じ有効値をどのように区別するかなど、error codeは使いにくい場合があります.
    2.2 exception handling
    The mission of exception handling is to transfer control from where the error occured to an error handler that can deal with the situation.
    エラーが発生した場合、プログラムはセキュリティ状態に戻り、再実行するか、現在の作業のセキュリティ終了を保存する必要がありますが、これは容易ではありません.重要なのは、プログラム制御権がエラーをトリガーした場所からエラーを処理する場所にどのようにジャンプするかです.
    Java allows every method an alternative exit path if it is unable to complete its task in the normal way:
  • まず、throws an object that encapsulates the error information
  • そして、the exception-handling mechanism begins its search for an exception handler that can deal with this particular error condition
  • 注意、このalternative exit pathは正常なプログラムロジックとは関係なく、the method exits immediately、and it does not return its normal value、and the execution does not resume at the code that called the method
  • 3. Java exception hierarchy
    3.1 Throwable
    ThrowableはJava exception hierarchy全体のベースクラスで、以下に分けられます.
  • Error
  • Exception

  • 3.2 Error
    the error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime system.
    You should not throw an object of this type. There is little you can do if sucn an internal error occurs, beyond notifying the user and trying to terminate the program gracefully.
    3.3 Exception
    Exceptionは、次の2つに分類されます.
  • RuntimeException
  • その他
  • RuntimeExceptionは、a bad cast、an out-of-bounds array access、a null pointer accessなどの符号化エラーを意味します.
    他のExceptionでは、通常、存在しないファイルを開くなど、何らかの事故が発生します.
    なぜ存在しないファイルを開くのはRuntimeExceptionではないのですか?これはあなたのコードが制御できるものではないので、まずファイルが存在するかどうかを検証しても無駄です.検証時に存在するかもしれませんが、開くと存在しません.
    4. Checked exception vs unchecked exception
    ErrorとRuntimeExceptionの2本をunchecked exceptionと呼びます.
    ErrorとRuntimeExceptionの2つを除いた他のExceptionはchecked exceptionと呼ばれています.
    The compiler checks that you provide exception handlers for all checked exceptions:
  • Errorに対して、あなたは何もできないので、unchecked exception
  • です.
  • RuntimeExceptionでは、符号化エラーはあなたの責任です.それを避けるべきです.だからunchecked exception
  • です.
  • 他のexceptionsについては、それらを処理する準備が必要ですので、checked exception
  • です.
    5. Checked exception declaration
    あなたの方法で投げ出す可能性のあるchecked exceptionsについては、method declarationでthrowsで宣言する必要があります.
    複数のchecked exceptionsを投げ出す可能性がある場合は、カンマで区切る必要があります.
    public Image loadImage(String name) throws FileNotFoundException, EOFException {...}

    unchecked exceptionはthrows声明に表示されるべきではありません.
  • Errorに対して、あなたはどうすることもできません
  • RuntimeExceptionでは、宣言ではなく、それらが投げ出される可能性があることを避ける必要があります.

  • 6. Throw an exception
    どのようにexceptionを投げ出しますか?簡単:
  • find an appropriate exception class
  • make an object of that class
  • throw it

  • 適切なstandard exception classはありませんか?いいえ、カスタマイズできます.
    class FileFormatException extends IOException {
        public FileFormatException() {}
        public FileFormatException(String gripe) {
            super(gripe);
        }
    }

    一般的に、カスタムexception classには2つのconstructors:a default constructor and a constructor with a detailed messageを提供します.
    7. Catch exceptions
    try {
        xxx
    } catch (ExceptionType1 | ExceptionType 2 e) {
        xxx
    } catch (ExceptionType3 e) {
        xxx
    }

    checked exceptionsでは、それらをどのように処理するかを知っていれば、catchすることができます.そうすれば、それらを投げ出す必要はありません.
    As a general rule, you should catch those exceptions that you know how to handle and propagate those that you do not know how to handle.
    8. Rethrow exceptions
    try {
        xxx
    } catch (SQLException e) {
        throw new ServletException("xxx error").initCause(e);
    }

    これはrethrow exceptionの一般的な方法です.このようにして、より抽象的なexceptionをパッケージしたり、checked exceptionをRuntimeExceptionに変換したりすることができます.
    9. finally
    try {
        try {
            xxx
        } finally {
            xxx
        }
    } catch (Exception e) {
        xxx
    }

    the inner try block has a single responsibility: to make sure that the resources are released
    the outer try block has a single responsibility: to ensure that errors are reported.
    注意、the body of the finally clause is intended for cleaning up resources.Don't put statements that change the control flow (return, throw, break, continue) inside a finally clause.
    10. try-with-Resources
    try (Resource res = xxx) {
        xxx
    }

    Java 7からtry-finally構造をtry-with-resourcesに簡略化できる.
    ResourceはAutoCloseableの実装クラスである必要があります.when the try block exits,then res.close()is called automatically.
    A difficulty arises when the try block throws an exception and the close method also throws an exception. The original exception is rethrown, and any exceptions thrown by close methods are considered "suppressed". They are automatically caught and added to the original exception with the addSuppressed method.