Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách tạo custom unchecked exception trong Java

Chúng ta có thể tạo custom unchecked exception bằng cách kế thừa RuntimeException trong Java.

Unchecked exceptions kế thừa từ lớp Error hoặc RuntimeException. Nhiều lập trình viên cho rằng không thể xử lý các ngoại lệ này vì chúng đại diện cho lỗi mà chương trình không thể khôi phục khi chạy. Khi unchecked exception bị ném, thường do sử dụng sai code, truyền null hoặc tham số không đúng.

Cú pháp cơ bản

public class MyCustomException extends RuntimeException { 
    public MyCustomException(String message) { 
        super(message); 
    } 
}

Triển khai Unchecked Exception đầy đủ

Gần giống checked exception, khác ở chỗ extends RuntimeException thay vì Exception.

Ví dụ đầy đủ

public class CustomUncheckedException extends RuntimeException { 
    /* 
     * Constructor với message tùy chỉnh 
     * Dùng: throw new CustomUncheckedException("Custom Unchecked Exception"); 
     */ 
    public CustomUncheckedException(String message) { 
        super(message); 
    } 
    
    /* 
     * Constructor wrap exception khác (cause) 
     * Dùng: catch(ArrayIndexOutOfBoundsException e) { throw new CustomUncheckedException(e); } 
     */ 
    public CustomUncheckedException(Throwable cause) { 
        super(cause); 
    } 
    
    /* 
     * Constructor vừa có message vừa có cause 
     * Dùng: throw new CustomUncheckedException(e, "File not found"); 
     */ 
    public CustomUncheckedException(String message, Throwable throwable) { 
        super(message, throwable); 
    } 
}

Ví dụ sử dụng

public class TestCustomException { 
    public static void main(String[] args) { 
        try { 
            validateAge(-5); 
        } catch (CustomUncheckedException e) { 
            System.out.println("Caught: " + e.getMessage()); 
        } 
    } 
    
    static void validateAge(int age) { 
        if (age < 0) { 
            throw new CustomUncheckedException("Age cannot be negative: " + age); 
        } 
    } 
}

Lưu ý

  • Unchecked exception không bắt buộc khai báo trong throws hay bắt buộc try-catch.
  • Dùng cho lỗi lập trình (bug), điều kiện tiền đề vi phạm, trạng thái không hợp lệ không thể khôi phục.
  • Tuân theo quy ước đặt tên: kết thúc bằng Exception (ví dụ: InvalidAgeException).