zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    视频质量诊断之详解
    Leetcode 22.生成括号对数
    leetcode 19.删除链表的第n个节点
    Leetcode 11.盛最多水的容器
    Leetcode 6.Z字形变换
    Leetcode 4.两个排序数组的中位数
    Leetcode 3.无重复字符的最长子串
    Leetcode 1.两数之和
    RNN and Language modeling in TensorFlow
    Tensorflow word2vec+manage experiments
  • 原文地址:https://www.cnblogs.com/liudianjia/p/12597481.html
Copyright © 2011-2022 走看看