转载自:http://blog.csdn.net/u013142781/article/details/50609488
真正工作了才发现,Java里面的异常在真正工作中使用还是十分普遍的。什么时候该抛出什么异常,这个是必须知道的。
当然真正工作里面主动抛出的异常都是经过分装过的,自己可以定义错误码和异常描述。
在给出异常分装例子之前,需要给大家普及Java里面的checked异常和unchecked异常的个概念。
一、checked异常和unchecked异常
这里之所以让大家清楚checked异常和unchecked异常概念,是因为:待会我们的异常是继承unchecked异常RuntimeException的。了解一下并无坏处嘛
checked异常:
表示无效,不是程序中可以预测的。比如无效的用户输入,文件不存在,网络或者数据库链接错误。这些都是外在的原因,都不是程序内部可以控制的。
必须在代码中显式地处理。比如try-catch块处理,或者给所在的方法加上throws说明,将异常抛到调用栈的上一层。
继承自java.lang.Exception(java.lang.RuntimeException除外)。
unchecked异常:
表示错误,程序的逻辑错误。是RuntimeException的子类,比如IllegalArgumentException, NullPointerException和IllegalStateException。
不需要在代码中显式地捕获unchecked异常做处理。
继承自java.lang.RuntimeException(而java.lang.RuntimeException继承自java.lang.Exception)。
看下面的异常结构图或许层次感更加深些:
二、异常分装实例
2.1、添加一个枚举LuoErrorCode.java如下:
package com.cctvjiatao.Enum;
/**
* 添加一个枚举
* @author keletao
*重写了LuoErrorCode的toString方法,至于为什么要这样,后面会提到
*/
public enum LuoErrorCode {
NULL_OBJ("LUO001", "对象为空"),
ERROR_ADD_USER("LUO002", "添加用户失败"),
UNKNOWN_ERROR("LUO999", "系统繁忙,请稍后再试....");
private String value;
private String desc;
private LuoErrorCode(String value, String desc) {
this.setValue(value);
this.setDesc(desc);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "[" + this.value + "]" + this.desc;
}
}
package com.cctvjiatao.Enum;
/**
* 创建一个异常类BusinessException.java,继承RuntimeException
* @author keletao
* 这里的代码虽然短,但是有两点需要注意的:
* 第一点是其继承了RuntimeException,因为一般我们的业务异常都是运行时异常
* 第二点,这里的构造方法调用父方法super(Obj.toString()); 这就是重写了LuoErrorCode的toString方法的原因了,如果还不明白,看完后面的你就明白了。
*/
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BusinessException(Object Obj) {
super(Obj.toString());
}
}
package com.cctvjiatao.Enum;
/**
* 测试类
* @author keletao
*/
public class ExceptionTest {
public static void main(String args[]) {
Object user1 = null;
if(user1 == null){
throw new BusinessException(LuoErrorCode.NULL_OBJ);
}
/*Object user2 = "cctv";
if(user2 == "cctv"){
throw new BusinessException(LuoErrorCode.ERROR_ADD_USER);
}*/
/*Object user3 = "busy";
if(user3 == "busy"){
throw new BusinessException(LuoErrorCode.UNKNOWN_ERROR);
}*/
}
}
【运行结果】:
Exception in thread "main" com.cctvjiatao.Enum.BusinessException: [LUO001]对象为空
at com.cctvjiatao.Enum.ExceptionTest.main(ExceptionTest.java:12)