异常(Exception)处理
本文地址:http://blog.csdn.net/caroline_wendy
Java异常(Exception)处理,会生成一个异常对象,使用抛出异常(throws Exception)的方式,跳转程序,
执行catch()部分代码,无论异常是否被抛出,finally块中代码始终会在catch或try后执行。
测试程序:
/**
* @author wangchenlong
*
*/
public class SimpleExampleWErrorHandling {
private int number;
public SimpleExampleWErrorHandling() {}
public void setValueWithException(int val) throws Exception {
if (val < 0)
throw new Exception("setValue Exception - Value that is set is Negative!");
number = val;
}
public int getNumber() {
return number;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return number+"";
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=0; i<10; i++) {
SimpleExampleWErrorHandling example = new SimpleExampleWErrorHandling();
if (i/2 <=2) {
try {
example.setValueWithException(i);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
example.setValueWithException(i*10);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("SimpleExample #" + i + "'s value is " + example.getNumber());
}
showErrorHandling();
}
public static void showErrorHandling() {
try {
System.out.println();
System.out.println("SimpleExample BadValue Insert Case Start");
SimpleExampleWErrorHandling example = new SimpleExampleWErrorHandling();
example.setValueWithException(-10);
System.out.println("SimpleExample BadValue's value is " + example.getNumber()); //不会执行
System.out.println("SystemExample BadValue Insert Case End"); //不会执行
} catch (Exception e) {
System.err.println("SimpleExample BadValue Insert Case threw an exception");
e.printStackTrace();
} finally {
System.out.println("SimpleExample BadValue " + "Insert Case Finally Called.");
}
}
}
输出:
SimpleExample #0's value is 0
SimpleExample #1's value is 1
SimpleExample #2's value is 2
SimpleExample #3's value is 3
SimpleExample #4's value is 4
SimpleExample #5's value is 5
SimpleExample #6's value is 60
SimpleExample #7's value is 70
SimpleExample #8's value is 80
SimpleExample #9's value is 90
SimpleExample BadValue Insert Case Start
SimpleExample BadValue Insert Case threw an exception
java.lang.Exception: setValue Exception - Value that is set is Negative!
at SimpleExampleWErrorHandling.setValueWithException(SimpleExampleWErrorHandling.java:17)
at SimpleExampleWErrorHandling.showErrorHandling(SimpleExampleWErrorHandling.java:64)
at SimpleExampleWErrorHandling.main(SimpleExampleWErrorHandling.java:55)
SimpleExample BadValue Insert Case Finally Called.