黑马程序员技术交流社区
标题:
关于异常..
[打印本页]
作者:
天空之城°
时间:
2014-4-9 09:55
标题:
关于异常..
自定义异常在实际项目当中会经常用到吗?
作者:
lren
时间:
2014-4-9 10:29
1、自定义异常
package heima.demo;
/**
* 负数异常
*
* 自定义异常
* @author lren
*
*/
public class NegativeException extends Exception {
private static final long serialVersionUID = -5935177486391324676L;
public NegativeException() {
super();
}
public NegativeException(String message, Throwable cause) {
super(message, cause);
}
public NegativeException(String message) {
super(message);
}
public NegativeException(Throwable cause) {
super(cause);
}
}
复制代码
2、异常使用
package heima.demo;
/**
* 异常使用
* @author lren
*
*/
public class NegativeExceptionDemo {
public static void main(String[] args) {
try {
test(2, 1);
} catch (NegativeException e) {
e.printStackTrace();
}
}
public static void test(int num1, int num2) throws NegativeException {
if (num2 - num1 < 0) {
throw new NegativeException("num1(" + num1 + ")应该小于 num2(" + num2 + ")");
}
}
}
复制代码
自定义异常是为了更贴切的解决生活中遇到的不同问题。因此,对于自定义异常要懂得,会使用。
作者:
天空之城°
时间:
2014-4-9 21:16
恩恩 明白了谢谢!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2