黑马程序员技术交流社区

标题: 关于异常.. [打印本页]

作者: 天空之城°    时间: 2014-4-9 09:55
标题: 关于异常..
自定义异常在实际项目当中会经常用到吗?
作者: lren    时间: 2014-4-9 10:29
1、自定义异常
  1. package heima.demo;

  2. /**
  3. * 负数异常
  4. *
  5. * 自定义异常
  6. * @author lren
  7. *
  8. */
  9. public class NegativeException extends Exception {

  10.         private static final long serialVersionUID = -5935177486391324676L;

  11.         public NegativeException() {
  12.                 super();
  13.         }

  14.         public NegativeException(String message, Throwable cause) {
  15.                 super(message, cause);
  16.         }

  17.         public NegativeException(String message) {
  18.                 super(message);
  19.         }

  20.         public NegativeException(Throwable cause) {
  21.                 super(cause);
  22.         }

  23. }
复制代码


2、异常使用
  1. package heima.demo;

  2. /**
  3. * 异常使用
  4. * @author lren
  5. *
  6. */
  7. public class NegativeExceptionDemo {

  8.         public static void main(String[] args) {
  9.                 try {
  10.                         test(2, 1);
  11.                 } catch (NegativeException e) {
  12.                         e.printStackTrace();
  13.                 }
  14.         }

  15.         public static void test(int num1, int num2) throws NegativeException {
  16.                 if (num2 - num1 < 0) {
  17.                         throw new NegativeException("num1(" + num1 + ")应该小于 num2(" + num2 + ")");
  18.                 }
  19.         }
  20. }
复制代码



自定义异常是为了更贴切的解决生活中遇到的不同问题。因此,对于自定义异常要懂得,会使用。
作者: 天空之城°    时间: 2014-4-9 21:16
恩恩 明白了谢谢!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2