灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2386回复:0

Java程序发生异常就挂了吗?

楼主#
更多 发布于:2012-09-08 09:40

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.NullPointerException
最后总要做的一件事。。。
>>>> 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之外的语句块。




喜欢0 评分0
游客

返回顶部