When handling exceptions, you should distinguish between checked exceptions and unchecked exceptions. For checked exceptions, we should provide robust exception recovery mechanisms, and for unchecked exceptions, this is a programming error, a bug, which should be well discovered and handled during the debugging phase.
1. Java Exception hierarchy
The above illustration (note: The figure quoted in http://dev2dev.bea.com.cn/techdoc/200702364792.html) identifies the Java exception hierarchy, and also indicates which exceptions are unchecked and which are checked. Here are a few common exception handling agents that attempt to summarize how exceptions should be handled in daily development.
2. Recovery mechanism for checked anomalies
Checked anomaly is not a programming error, and its appearance is unavoidable in the software running phase. The most common type of exception is the socket connection timeout.
For such exceptions, we should try to recover from the exception in the running state of the program. The main logic of the following code (RECOVER.JAVA) is to judge the target value protected int current, or to throw a Notbigenoughexception exception if the value is greater than 2.
In the process of executing a program, we increment the current value every time catch to Notbigenoughexception exception, trying to recover from the exception.
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();
}
}
}
}
Results:
com.zj.exception.types.NotBigEnoughException: reject 0
com.zj.exception.types.NotBigEnoughException: reject 1
com.zj.exception.types.NotBigEnoughException: reject 2
accept 3