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


    Java程序发生异常就挂了吗?
     
    为了验证程序不会挂,我写了个例子给大家看看。
     
    测试代码:
     
    import java.io.File;
    import java.io.IOException;

    /**
    * Java程序发生异常就挂了吗?
    *
    * @author leizhimin,2008-10-10 15:18:26
    */

    public class TestException {
            public static void 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
             */

            public void test1() throws IOException {
                    throw new 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之外的语句块。
     

    https://www.jianshu.com/p/6bbd833bbfd4

    https://www.jianshu.com/p/1cd7c3c81bca

    https://www.jianshu.com/p/d759f3878e73

    https://www.jianshu.com/p/ae4e3a5f4f69

    https://www.jianshu.com/p/db24986b85b9

    https://www.jianshu.com/p/3d445cd7d1e5

    https://www.jianshu.com/p/98f96a93d7ca

  • 相关阅读:
    python 协程
    python 打印乘法表
    python 线程池
    python 队列
    开发react 应用最好用的脚手架 create-react-app
    React面试题
    修改了背景透明度
    低门槛彻底理解JavaScript中的深拷贝和浅拷贝
    Web Worker 使用教程
    Vue2 实现时空穿梭框功能模块
  • 原文地址:https://www.cnblogs.com/liudianjia/p/12597481.html
Copyright © 2020-2023  润新知