Java 例外の詳細

PHPz
リリース: 2024-08-19 06:01:02
オリジナル
404 人が閲覧しました

Javaコア例外クラス

例外クラスの階層: Throwable

エラー 投擲可能

Throwable クラスは、Java 言語のすべてのエラーと例外のスーパークラスです。このクラス (またはそのサブクラスの 1 つ) のインスタンスであるオブジェクトのみが Java 仮想マシンによってスローされるか、Java throw ステートメントによってスローできます。参考


実際には、Throwable は通常、開発者によって直接使用されることはありません。代わりに、それは 2 つの直接のサブクラス、Error と Exception の基盤として機能します。

try {
 // some process
} catch (Throwable t) {
    throw new Throwable(t);
}
ログイン後にコピー

エラー

Error は Throwable のサブクラスで、合理的なアプリケーションが検出すべきではない重大な問題を示します。エラーは通常、JVM 自体で発生する異常な状態を表します。

異常な状態とは、通常、アプリケーションの制御外の要因によって問題が発生し、通常は回復不可能であることを意味します。例: OutOfMemoryError、StackOverflowError

Deep Dive into Java Exceptions

例外

例外とは、プログラムの実行中に発生する予期しないイベントまたは条件を指します。キャッチを試みる必要があります。例外をキャッチすることで、予期せぬ状況を適切に処理し、プログラムがクラッシュしないようにできるはずです。

int[] arr = {1, 2, 3};
try {
    System.out.println(arr[3]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Unchecked Exception: " + e.getMessage());
}
ログイン後にコピー

例外の種類

Javaには2種類の例外があります。参考

チェックされた例外

チェック例外は、問題が発生する可能性があることがわかっている状況に似ているため、計画を立てる必要があります。これらは、try-catch ブロックを使用してキャッチするか、メソッド シグネチャ内で throws 節を使用して宣言する必要があります。メソッドがチェック例外をスローする可能性があり、それを処理しない場合、プログラムはコンパイルされません。

// Checked exception
try {
    readFile("nonexistent.txt");
} catch (FileNotFoundException e) {
    System.out.println("Checked Exception: " + e.getMessage());
}
ログイン後にコピー
// Checked exception
public void getData() throws SQLException { // throw SQLException
    throw new SQLException("err");
}
ログイン後にコピー

未チェックの例外

未チェック例外、別名。実行時例外は、Java コンパイラーが処理する必要のない例外です。これらは RuntimeException のサブクラスです。チェック例外とは異なり、これらの例外をキャッチしたり、メソッド シグネチャで宣言したりする必要はありません。これらは通常、ロジックの欠陥、API の誤った使用、コード内の前提条件の違反などのプログラミング エラーを示します。

String text = null;
System.out.println(text.length()); // This will throw a NullPointerException
ログイン後にコピー

Java 例外の一般的なタイプ

NullPointerException: アプリケーションが初期化されていないオブジェクト参照を使用しようとすると発生します。

String text = null; // text is not initialized
try {
    System.out.println(text.length()); // Attempting to call length() on a null reference
} catch (NullPointerException e) {
    System.out.println("Caught a NullPointerException: " + e.getMessage());
}
ログイン後にコピー

ArrayIndexOutOfBoundsException: 不正なインデックスを持つ配列にアクセスしようとするとスローされます。

int[] numbers = {1, 2, 3};
try {
    int value = numbers[5]; // Attempting to access index 5, which is out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}
ログイン後にコピー

IllegalArgumentException: メソッドが不適切な引数を受け取ったときにスローされます。

public class IllegalArgumentExample {
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative"); // Illegal argument
        }
        System.out.println("Age set to: " + age);
    }

    public static void main(String[] args) {
        try {
            setAge(-5); // Passing a negative age, which is illegal
        } catch (IllegalArgumentException e) {
            System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
        }
    }
}
ログイン後にコピー

例外を処理する方法

トライキャッチ

コード ブロック内でスローされる可能性のある特定の例外を処理する場合は、try-catch を使用します

try {
    int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Caught an ArithmeticException: " + e.getMessage());
}
ログイン後にコピー

マルチキャッチ

複数の例外タイプを同様の方法で処理したい場合は、マルチキャッチを使用します

try {
    String str = null;
    System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Caught an exception: " + e.getMessage());
}
ログイン後にコピー

リソースを試す

ファイル、ソケット、データベース接続など、使用後に閉じる必要があるリソースを操作する場合は、try-with-resources を使用します。

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
}
ログイン後にコピー

ついに

例外がスローされたかどうかに関係なく、特定のコードが確実に実行されるようにする必要がある場合は、finally ブロックを使用します

try {
    file = new FileReader("file.txt");
} catch (IOException e) {
    System.out.println("Caught an IOException: " + e.getMessage());
} finally {
    if (file != null) {
        file.close(); // Ensure the file is closed
    }
}
ログイン後にコピー

例外処理のベストプラクティス

例外を無視しないでください: 例外は、単に捕らえて無視するのではなく、適切に処理する必要があります。

try {
    file = new FileReader("file.txt");
} catch (IOException ignored) {
    // ignored
}
ログイン後にコピー

特定の例外を使用する: 一般的な例外を使用するのではなく、特定の例外を使用します。

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (Exception e) {
    // Too broad; will catch all exceptions
    System.err.println("An error occurred: " + e.getMessage());
}
ログイン後にコピー

適切な対処方法:

try {
    // Code that may throw exceptions
    String text = null;
    text.length();
} catch (NullPointerException e) {
    // Handle specific exception
    System.err.println("Null pointer exception: " + e.getMessage());
} catch (Exception e) {
    // Handle other exceptions
    System.err.println("An error occurred: " + e.getMessage());
}
ログイン後にコピー

クリーンなリソース処理: メモリ リークを避けるために常にリソースを閉じます

FileReader fileReader = null;
try {
    fileReader = new FileReader("file.txt");
    // Read from the file
} catch (IOException e) {
    System.err.println("File not found: " + e.getMessage());
} finally {
   fileReader.close(); // clouse resources
}
ログイン後にコピー

カスタム例外: 標準例外が特定のエラー条件に適合しない場合にカスタム例外を作成します。

// Custom Exception
public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

// Usage
public class Example {
    public void performOperation() throws CustomException {
        // Some condition
        throw new CustomException("Custom error message");
    }

    public static void main(String[] args) {
        Example example = new Example();
        try {
            example.performOperation();
        } catch (CustomException e) {
            System.err.println("Caught custom exception: " + e.getMessage());
        }
    }
}
ログイン後にコピー

ログ: デバッグとメンテナンスのために例外をログに記録します。

public class Example {
    private static final Logger logger = Logger.getLogger(Example.class.getName());

    public void riskyMethod() {
        try {
            // Code that may throw an exception
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // Log the exception
            logger.severe("An arithmetic error occurred: " + e.getMessage());
        }
    }
}
ログイン後にコピー

例外の過度の使用を避ける: フローを制御するために例外を使用しないように警告します。これらは、本当に例外的な状況を処理する場合にのみ使用する必要があります。

public class Example {
    public void process(int[] array) {
        try {
            // Using exceptions to control flow
            if (array.length < 5) {
                throw new ArrayIndexOutOfBoundsException("Array too small");
            }
            // Process array
        } catch (ArrayIndexOutOfBoundsException e) {
            // Handle exception
            System.out.println("Handled array size issue.");
        }
    }
}
ログイン後にコピー

適切な対処方法:

public class Example {
    public void process(int[] array) {
        if (array.length >= 5) {
            // Process array
        } else {
            // Handle the condition without using exceptions
            System.out.println("Array is too small.");
        }
    }
}
ログイン後にコピー


フィードバックは役に立ちます:)

以上がJava 例外の詳細の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!