Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จัดการ IllegalArgumentException ด้วย If Statement ใน Java

แนวคิด

แทนที่จะ Catch Exception ให้ Validate Input ก่อนเรียก Method ที่อาจโยน IllegalArgumentException โดยใช้ if-check เงื่อนไขที่รู้ล่วงหน้า

ตัวอย่าง: Thread.setPriority()

setPriority(int) โยน IllegalArgumentException ถ้าค่าน้อยกว่า 1 (MIN_PRIORITY) หรือมากกว่า 10 (MAX_PRIORITY)

import java.util.Scanner;

public class IllegalArgumentExample {
    public static void main(String args[]) {
        Thread thread = new Thread();
        System.out.println("Enter the thread priority value (1-10):");
        Scanner sc = new Scanner(System.in);
        int priority = sc.nextInt();

        if (priority >= Thread.MIN_PRIORITY && priority <= Thread.MAX_PRIORITY) {
            thread.setPriority(priority);
            System.out.println("Priority set to: " + priority);
        } else {
            System.out.println("Priority value must be between " + Thread.MIN_PRIORITY + " and " + Thread.MAX_PRIORITY);
        }
    }
}

ผลลัพธ์

Enter the thread priority value (1-10):
15
Priority value must be between 1 and 10

ข้อดีของการ Validate ก่อน

  • หลีกเลี่ยง Exception Overhead (Stack trace, Unwinding)
  • Code อ่านง่าย กำหนดเงื่อนไขชัดเจน
  • User Experience ดีขึ้น (Error Message ใส่ใจได้)
  • เป็น Defensive Programming

เมื่อไหร่ควรใช้ Try-Catch แทน?

  • เงื่อนไขซับซ้อน/ไม่รู้ล่วงหน้า
  • Library/Third-party code ที่ไม่รู้ Validation Rules
  • Race Condition (Check-then-act ไม่ Atomic)