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

Custom Exceptions ใน Java

คุณสามารถสร้าง Exception ของตัวเองใน Java ได้ ซึ่งเรียกว่า User-defined exceptions หรือ Custom exceptions

เพื่อสร้าง user-defined exception ให้ขยาย (extends) คลาสที่กล่าวมาข้างต้น เพื่อแสดงข้อความ ให้ override เมธอด toString() หรือ เรียก constructor ของซูเปอร์คลาสพร้อมส่งข้อความในรูปแบบ String

MyException(String msg){
    super(msg);
}
หรือ
public String toString(){
    return " MyException [ข้อความของ exception ของคุณ]";
}

จากนั้น ในคลาสอื่นๆ ที่ต้องการให้ exception นี้เกิดขึ้น ให้สร้างอ็อบเจกต์ของคลาส custom exception ที่สร้างไว้ และ โยน (throw) exception โดยใช้คียเวิร์ด throw

MyException ex = new MyException();
if(condition...){
    throw ex;
}

Custom Checked และ Custom Unchecked

  • Exception ทั้งหมดต้องเป็นลูกของ Throwable
  • ถ้าต้องการเขียน checked exception ที่บังคับโดยกฎ Handle or Declare ให้ extends คลาส Exception
  • ถ้าต้องการเขียน runtime exception ให้ extends คลาส RuntimeException

ตัวอย่าง: Custom Checked Exception

โปรแกรม Java ต่อไปนี้สาธิตวิธีสร้าง Custom checked exception

import java.util.Scanner;

class NotProperNameException extends Exception {
    NotProperNameException(String msg){
        super(msg);
    }
}

public class CustomCheckedException {
    private String name;
    private int age;
    
    public static boolean containsAlphabet(String name) {
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (!(ch >= 'a' && ch <= 'z')) {
                return false;
            }
        }
        return true;
    }
    
    public CustomCheckedException(String name, int age){
        if(!containsAlphabet(name) && name != null) {
            String msg = "Improper name (Should contain only characters between a to z (all small))";
            NotProperNameException exName = new NotProperNameException(msg);
            throw exName;
        }
        this.name = name;
        this.age = age;
    }
    
    public void display(){
        System.out.println("Name of the Student: " + this.name);
        System.out.println("Age of the Student: " + this.age);
    }
    
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the name of the person: ");
        String name = sc.next();
        System.out.println("Enter the age of the person: ");
        int age = sc.nextInt();
        CustomCheckedException obj = new CustomCheckedException(name, age);
        obj.display();
    }
}

ข้อผิดพลาดตอนคอมไพล์ (Compile-time exception)

ตอนคอมไพล์ โปรแกรมข้างต้นจะสร้าง exception ดังนี้:

CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown
    throw exName;
    ^
1 error

ตัวอย่าง: Custom Unchecked Exception

ถ้าเปลี่ยนคลาสที่ custom exception สืบทอดมาเป็น RuntimeException จะกลายเป็น exception ที่โยนตอนรันไทม์

class NotProperNameException extends RuntimeException {
    NotProperNameException(String msg){
        super(msg);
    }
}

รันโปรแกรมก่อนหน้าโดยแทนที่ NotProperNameException ด้วยโค้ดด้านบน จะได้ runtime exception ดังนี้:

Runtime Exception

Enter the name of the person: Krishna1234
Enter the age of the person: 20
Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
    at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25)
    at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)