ホームページ  >  記事  >  Java  >  Java例外処理

Java例外処理

WBOY
WBOYオリジナル
2024-08-28 06:37:02388ブラウズ

Java Exception Handling

基本

例外を理解する: 問題が発生した場合はどうなりますか?

ゲームをプレイしているときに、突然キャラクターが穴に落ちたと想像してください。あなたならどうしますか?おそらくゲームを再開するか、次回はピットを回避する方法を見つけるでしょう。プログラミングでも、同様のことが起こる可能性があります。コードが例外と呼ばれる「落とし穴」に陥る可能性があります。その場合、プログラムが動作を停止したり、予期しない動作が発生したりする可能性があります。

例外とは正確には何ですか?

例外は、コードの実行中に何か問題が発生したことを示す信号のようなものです。おそらく、数値をゼロで除算しようとしたか (これは許可されていません)、存在しないファイルを開こうとしたのかもしれません。これらの問題が発生すると、Java はフラグを立てて「おい! ここに問題がある!」と伝えます

例外処理がないとどうなりますか?

例外を処理しないと、プログラムがクラッシュし、すべての進行状況が失われる可能性があります。これは、ゲームを保存せずにコンピューターの電源が突然切れた場合と同じです。

例を見てみましょう:

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;
        int result = number / 0; // This will cause an exception!
        System.out.println("Result: " + result); // This line will never be reached.
    }
}

このコードを実行しようとすると、コードは停止して「ゼロで割ることはできません!」と文句を言います。

どうすればその穴を避けることができますか?

この問題を回避するために、Java は try and catch と呼ばれるものを提供します。

  • ブロックを試みる: ここでは、問題を引き起こす可能性のある何かを実行しようとします。
  • catch Block: 問題が発生した場合にこれをキャッチし、プログラムがクラッシュしないようにします。

例を書き直してみましょう:

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;

        try {
            int result = number / 0; // We know this might cause a problem.
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}

現在何が起こっているかは次のとおりです:

  • try ブロックはゼロによる除算を試みます。
  • Java が問題を認識すると、catch ブロックにジャンプして、「おっと! ゼロで割ることはできません。」

さまざまな問題を解決する

例外のキャッチの詳細

例外をキャッチする方法がわかったので、「コードにさまざまな種類の問題が発生する可能性がある場合はどうすればよいでしょうか? それらすべてをキャッチするにはどうすればよいですか?」と疑問に思うかもしれません。

ゲームで宝箱を開けようとしていると想像してください。場合によっては、鍵が合わないこともありますし (これは 1 つの問題です)、また、チェストが空であることもあります (これは別の問題です)。何が問題だったのかを正確に知りたいですよね?

さまざまな種類の例外

Java には、さまざまな種類の問題、つまり例外があります。例:

  • ArithmeticException: ゼロで割るなど、意味のない計算を実行しようとしたとき。
  • NullPointerException: まだ存在しないものを使用しようとしたとき (存在しない宝箱を開けようとしたときなど)。
  • ArrayIndexOutOfBoundsException: 10 個しかない jar 内の 11 番目の Cookie を要求するなど、配列の制限を超えたものにアクセスしようとしたとき。

複数の例外をキャッチする

コード内のさまざまなタイプの問題を検出する方法を見てみましょう:

public class MultipleExceptionsExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException!
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! You tried to access an index that doesn’t exist.");
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}

以下のことが起こります:

  • try ブロック内のコードは、問題を引き起こす可能性のあることを実行しようとしています。
  • ArrayIndexOutOfBoundsException に遭遇した場合、最初の catch ブロックにジャンプします。
  • ArithmeticException に遭遇すると、2 番目の catch ブロックにジャンプします。

何か問題が発生した場合はどうすればよいですか?

何が問題になるのか分からないこともありますが、それでも問題を見つけたいと思うことがあります。一般的な例外を使用して、問題が発生したものを検出できます。

public class GeneralExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an ArithmeticException!
        } catch (Exception e) {
            System.out.println("Oops! Something went wrong.");
        }
    }
}

こうすることで、何か問題が発生しても catch ブロックが引き続き処理し、プログラムがクラッシュすることはありません。

カスタム例外のクリーンアップと作成

ついにブロック

ゲームをプレイしていて宝物を見つけたと想像してください。成功しても失敗しても、終わったら必ず宝箱を閉めたいと思うでしょう。 Java では、finally ブロックは、何が起こっても宝箱が常に閉まっていることを確認するようなものです。

finally ブロックとは何ですか?

finally ブロックは、例外が発生するかどうかに関係なく、常に実行されるコードです。ファイルを閉じる、タイマーを停止する、宝箱をしまうなど、クリーンアップするために使用されます。

例を見てみましょう:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an exception.
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        } finally {
            System.out.println("This will always run, no matter what.");
        }
    }
}

以下のことが起こります:

  • The try block tries to do something risky.
  • The catch block catches the problem if it happens.
  • The finally block always runs, even if there’s no problem.

Making Your Own Custom Exceptions

Sometimes, the problems you face in your code are special. Maybe the game doesn’t just have treasure chests, but also magical doors that can sometimes be locked. You might want to create a special exception for when the door is locked.

Creating a Custom Exception

You can create your own exceptions by making a new class that extends Exception. Let’s create an exception called LockedDoorException:

class LockedDoorException extends Exception {
    public LockedDoorException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            openDoor(false);
        } catch (LockedDoorException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void openDoor(boolean hasKey) throws LockedDoorException {
        if (!hasKey) {
            throw new LockedDoorException("The door is locked! You need a key.");
        }
        System.out.println("The door is open!");
    }
}

Here’s how it works:

  • We create a new exception called LockedDoorException.
  • When we try to open the door without a key, we throw the LockedDoorException.
  • The catch block catches our custom exception and tells us what went wrong.

Summary

In this post, we’ve learned that:

  • Exceptions are problems that happen when your code is running.
  • try and catch blocks help us handle these problems, so our program doesn’t crash.

  • Different types of exceptions are like different kinds of problems.

  • We can catch multiple exceptions to handle specific problems.

  • We can also catch any exception using the general Exception type.

  • The finally block is used to clean up, and it always runs no matter what.

  • You can create custom exceptions to handle special problems in your code.

And that it! Now you’re ready to handle any problem that comes your way in your code. If you have any questions, feel free to ask!

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

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。