java学习笔记62--抛出和捕获对程序的影响

   1)如果程序中的某行代码的执行抛出了异常,并且这个异常一直都没有被try-catch处理,那么这个异常最终会抛给JVM,JVM输出异常信息后就自动停止了
        例如:
        public static void main(String[] args) throws ClassNotFoundException {
            System.out.println("hello");
            Class.forName("test..");
            System.out.println("world");
            //....其他代码
        }
        
        最终的结果是代码在调用forName方法抛出异常后,JVM处理后就停止了.并没有往下继续执行代码
    
    2)如果使用try-catch语句去处理代码中抛出的异常,那么catch语句块处理完之后,代码还会在catch语句块下面继续执行
        例如:
        public static void main(String[] args){
            System.out.println("hello");
            try {
                Class.forName("test..");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("world");
            //....其他代码
        }
        最终的结果是catch语句执行完后,代码继续往下正常执行。
    

    3)try-catch语句块虽然能处理完异常后继续让代码往下执行,但是在某些时候也会改变代码的执行流程(默认是从上往下顺序执行)
        例如:
        public static void main(String[] args){
            System.out.println("hello");
            try {
                Class.forName("test..");
                System.out.println("world");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //....其他代码
        }

        最终的结果是catch语句执行完后,代码执行下面的其他代码,但是上面打印world的语句就跳过去了。

猜你喜欢

转载自blog.csdn.net/onepiece_loves/article/details/88707668