java程序发生异常就挂了吗?
为了验证程序不会挂,我写了个例子给
大家看看。
测试代码:
import
java.io.File;
import
java.io.IOException;
/**
*
java程序发生异常就挂了吗?
*
*/
publicclass TestException {
publicstaticvoid main(String[] args) {
TestException te = new TestException();
String s = te.test();
System.out.println(s);
}
/**
* 这个方法有异常,看看异常发生时候会不会执行到底,会不会返回个值?
*
* @return 一个字符串!
*/
public String test() {
System.out.println(">>>> start");
try {
test1();
File f = null;
f.delete();
// int x = 10;
// int y = 0;
// int z = x / y;
System.out.println("计算完成了!");
} catch (Exception e) {
System.out.println("出异常挂了我如何处理呢?");
System.out.println(e);
} finally {
System.out.println("最后总要做的一件事。。。");
}
System.out.println(">>>> end");
return"good!";
}
/**
* 抛个比较猛烈的异常看看程序会挂吗?
*
* @throws IOException
*/
publicvoid test1() throws IOException {
thrownew IOException();
}
}
运行结果:
>>>> start
出异常挂了我如何处理呢?
java.io.IOException
最后总要做的一件事。。。
>>>> end
good!
Process finished with exit code 0
换个异常运行看看:
>>>> start
出异常挂了我如何处理呢?
java.lang.NullPo
interException
最后总要做的一件事。。。
>>>> end
good!
Process finished with exit code 0
再换个控制针看看:
>>>> start
出异常挂了我如何处理呢?
java.lang.ArithmeticException: / by zero
最后总要做的一件事。。。
>>>> end
good!
Process finished with exit code 0
结果表明:程序仅仅跳过了try中发生异常以后的代码,在发生异常时候执行了处理语句块catch,在catch执行结束后接着执行了finally语句块,然后继续执行try...catch...finally之外的语句块。