User-defined Exception trong Java



Miêu tả vấn đề

Cách tạo User Defined Exception (exception được định nghĩa bởi người dùng) trong Java?

Giải pháp

Ví dụ sau minh họa cách tạo exception được định nghĩa bởi người dùng bởi kế thừa lớp Exception trong Java.

class WrongInputException extends Exception {
   WrongInputException(String s) {
      super(s);
   }
}
class Input {
   void method() throws WrongInputException {
      throw new WrongInputException("Wrong input");
   }
}
class TestInput {
   public static void main(String[] args){
      try {
         new Input().method();
      }
	  catch(WrongInputException wie) {
         System.out.println(wie.getMessage());
      }
   } 
}

Kết quả

Code trên sẽ cho kết quả sau:

Wrong input

exception_trong_java.jsp