Bạn có thể tạo exception riêng trong Java, gọi là user-defined exceptions hoặc custom exceptions.
Để tạo user-defined exception, extends một trong các class Exception. Để hiển thị message, override toString() hoặc gọi constructor có tham số của superclass với message String.
MyException(String msg){ super(msg); } Or, public String toString(){ return " MyException [Message of your exception]"; }
Sau đó, ở nơi cần ném exception, tạo object custom exception class và ném bằng từ khóa throw.
MyException ex = new MyException (); If(condition...){ throw ex; }
Custom Checked và Custom Unchecked
Tất cả exception phải là con của Throwable.
Muốn checked exception (bắt buộc handle/khai báo throws), extends Exception.
Muốn runtime exception, extends RuntimeException.
Ví dụ: Custom Checked exception
Chương trình Java sau demo tạo 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
Khi compile, chương trình sinh exception sau:
CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error
Ví dụ: Custom unChecked exception
Thay class cha thành RuntimeException thì exception ném tại runtime.
class NotProperNameException extends RuntimeException { NotProperNameException(String msg){ super(msg); } }
Chạy chương trình trước với class trên sẽ sinh 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)