Try và Catch

Kiểu dữ liệu và Exceptions trong Java

Jim White

Java Developer

Vấn đề trong Java

  • Ứng dụng có thể gặp vấn đề/sự cố
    • Do nhập sai
    • Do lỗi mã
    • Do tình huống bất ngờ
  • Các vấn đề/sự cố gọi là exception
    • Làm gián đoạn luồng điều khiển bình thường
  • Java ném ngoại lệ
Kiểu dữ liệu và Exceptions trong Java

Ví dụ về Exception

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Kiểu dữ liệu và Exceptions trong Java

Try

  • Bọc mã có thể phát sinh ngoại lệ bằng khối try
    • "Thử chạy mã này; nếu có vấn đề, chuyển sang catch"
try {
    // Các lệnh được theo dõi ngoại lệ
}
Kiểu dữ liệu và Exceptions trong Java

Catch

  • Đặt khối catch sau try
    • Hoạt động như trình xử lý ngoại lệ
    • Ngoại lệ bắt được truyền vào khối này như tham số
  • try/catch là bắt buộc cho một số kiểu ngoại lệ
    • Tùy chọn cho các kiểu khác
try {
    // Statements to be executed and watched for exceptions
} catch (<Exception type> <variable name>) {
    // Statements to execute if an exception has occurred
}
Kiểu dữ liệu và Exceptions trong Java

Bắt IndexOutOfBoundsException

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Kiểu dữ liệu và Exceptions trong Java

Nhiều Catch

  • Dùng nhiều catch để xử lý các kiểu ngoại lệ khác nhau
  • Mỗi catch có kiểu ngoại lệ và biến riêng
  • Khi có ngoại lệ, Java kiểm tra các catch theo thứ tự đến khi khớp
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Kiểu dữ liệu và Exceptions trong Java

Catch "tất cả"

  • Dùng catch (Exception variable){ } để bắt tất cả
    • Xử lý mọi ngoại lệ chưa được các catch khác xử lý
try {
    // Code to try
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // Handles all exceptions except the two above
    System.out.println("Something unplanned happened");
}
Kiểu dữ liệu và Exceptions trong Java

Finally

  • Khối finally luôn chạy
// Khi xảy ra ngoại lệ
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// Khi không có ngoại lệ
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Kiểu dữ liệu và Exceptions trong Java

Đối tượng Exception

  • Đối tượng Exception truyền vào catch chứa nhiều thông tin
  • Dùng các phương thức để biết lỗi gì xảy ra
    • .getMessage() lấy thông điệp dễ đọc
    • .getClass() lấy lớp/kiểu ngoại lệ
    • .printStackTrace() in stack trace (slide sau)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Kiểu dữ liệu và Exceptions trong Java

Stack trace của ngoại lệ

  • Stack trace ghi lại luồng thực thi đến điểm lỗi
    • Dưới đây: đầu ra từ ví dụ trước - gồm stack trace
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Kiểu dữ liệu và Exceptions trong Java

Ayo berlatih!

Kiểu dữ liệu và Exceptions trong Java

Preparing Video For Download...