Java 实例 - 自定义异常


以下实例演示了通过继承 Exception 来实现自定义异常:

  1. /*
  2. author by shouce.ren
  3. TestInput.java
  4. */
  5.  
  6. class WrongInputException extends Exception {
  7. WrongInputException(String s) {
  8. super(s);
  9. }
  10. }
  11. class Input {
  12. void method() throws WrongInputException {
  13. throw new WrongInputException("Wrong input");
  14. }
  15. }
  16. class TestInput {
  17. public static void main(String[] args){
  18. try {
  19. new Input().method();
  20. }
  21. catch(WrongInputException wie) {
  22. System.out.println(wie.getMessage());
  23. }
  24. }
  25. }

以上代码运行输出结果为:

  1. Wrong input