首頁 > Java > java教程 > 主體

Java異常處理

WBOY
發布: 2024-08-28 06:37:02
原創
388 人瀏覽過

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 和 catch 的東西。

  • 嘗試封鎖:這是您嘗試執行可能會導致問題的操作的地方。
  • catch 區塊: 這是您在發生問題時捕獲問題的地方,這樣您的程式就不會崩潰。

讓我們重寫我們的範例:

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 區塊並說:「哎呀!你不能除以零。」

捕捉不同的問題

有關捕獲異常的更多資訊

既然您知道如何捕獲異常,您可能會想,「如果我的程式碼可能存在不同類型的問題怎麼辦?我如何捕獲所有這些問題?」

想像一下您正在遊戲中嘗試打開一個寶箱。有時,鑰匙不合適(這是一個問題),有時,箱子是空的(這是另一個問題)。您肯定想知道到底出了什麼問題,對吧?

不同類型的異常

在 Java 中,有不同類型的問題,或 異常。例如:

  • ArithmeticException:當你嘗試做沒有意義的數學運算時,例如除以零。
  • NullPointerException:當您嘗試使用尚不存在的東西時(例如嘗試打開不存在的寶箱)。
  • ArrayIndexOutOfBoundsException:當您嘗試存取陣列以取得超出其限制的內容時,例如在只有 10 個的罐子中請求第 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,它會跳到第二個 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 區塊是一段無論是否發生異常都會始終運行的程式碼。它用於清理,例如關閉檔案、停止計時器或收起寶箱。

讓我們來看一個例子:

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!