A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 天空之城° 中级黑马   /  2014-4-9 09:55  /  601 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自定义异常在实际项目当中会经常用到吗?

2 个回复

倒序浏览
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. }
复制代码



自定义异常是为了更贴切的解决生活中遇到的不同问题。因此,对于自定义异常要懂得,会使用。

评分

参与人数 1技术分 +1 收起 理由
itpower + 1

查看全部评分

回复 使用道具 举报
恩恩 明白了谢谢!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马