Java:如何处理异常
时间:2011-03-14 zhangjunhd
在处理异常时,应该区分checked异常和unchecked异常。对于checked异常,我们应该提供健壮的异常恢复机制,而对于unchecked异常,这就是编程错误即bug,应该在调试阶段很好的发现和处理它们。
1. Java异常层次结构
上图(注:该图引自http://d***dev.bea.com.cn/techdoc/200702364792.html)标出了Java异常层次结构,也指出了哪些异常是unchecked,哪些异常是checked。下面给出几段常见的异常处理代理,试图总结日常开发中应该如何处理异常。
2.针对checked异常的恢复机制
checked异常并不是编程错误,它的出现是软件运行阶段所不可避免的。最常见的这类异常如socket连接超时。
对于此类异常,我们应该在程序的运行态下试图从异常中恢复过来。下面这段代码(Recover.java)的主要逻辑是,对目标值protected int current进行判断,如果该值大于2则成功,否则抛出NotBigEnoughException异常。
在执行程序的过程中,在每次catch到NotBigEnoughException异常时,我们对current值递增,试图从异常中恢复过来。
NotBigEnoughException.java
package com.zj.exception.types;
public class NotBigEnoughException extends Exception {
public NotBigEnoughException() {
super();
}
public NotBigEnoughException(String msg) {
super(msg);
}
}
Recover.java
package com.zj.exception;
import com.zj.exception.types.NotBigEnoughException;
public class Recover {
protected int current = 0;
protected boolean accept = false;
public Recover() {}
public Recover(int cur) {
current = cur;
}
public void increment() {
++current;
}
public boolean passed() {
return accept;
}
public void passing() throws NotBigEnoughException {
if (current > 2) {
accept = true;
System.out.println("accept " + current);
} else
throw new NotBigEnoughException("reject " + current);
}
public static void main(String[] args) {
Recover re = new Recover();
while (!re.passed()) {
try {
re.passing();
} catch (NotBigEnoughException e) {
System.out.println(e);
re.increment();
}
}
}
}
结果:
com.zj.exception.types.NotBigEnoughException: reject 0
com.zj.exception.types.NotBigEnoughException: reject 1
com.zj.exception.types.NotBigEnoughException: reject 2
accept 3
Java:如何处理异常(2)
时间:2011-03-14 zhangjunhd
3.继承异常
在子类继承父类的情况下,子类override方法的异常声明只能取自(小于等于)父类该方法的异常声明;对于子类构造方法的异常声明必须包含(大于等于)父类构造方法的异常声明。
类Inheritor继承自类Recover,它的方法passing()试图声明一个父类没有的异常UnknowException,这样做是不允许的。
UnknowException.java
package com.zj.exception.types;
public class UnknowException extends Exception {
public UnknowException() {
super();
}
public UnknowException(String msg) {
super(msg);
}
}
error in: Inheritor.java
//couldn''t throws new exceptions where not found in its base class
public void passing() throws NotBigEnoughE
|