zoukankan      html  css  js  c++  java
  • finally语句块一定会被执行吗

    finally语句块一定会被执行吗? 答案: 不一定

    1. 发生异常的代码必须在try 代码块中,才有可能被执行

    public class MyTest {
    
        public static void main(String[] args) {
    
            System.out.println("main 代码块中的执行结果为:" + myMethod());
        }
    
        public static int myMethod() {
    
            int i = 0;
            int[] num = { 1, 2, 3 };
    
    
            System.out.println(num[3]);
            try {
                System.out.println("try 代码块被执行!");
                return 0;
            } catch (Exception e) {
                System.out.println("catch 代码块被执行!");
                return 0;
            } finally {
                System.out.println("finally 代码块被执行!");
    return 2; } } }

    2. 

    public class MyTest {
     
        public static void main(String[] args) {
     
            System.out.println("main 代码块中的执行结果为:" + myMethod());
        }
     
        public static int myMethod() {
     
            int i = 6;
            try {
                System.out.println("try 代码块被执行!");
     
                //i = i/0;
     
                return 1;
            } catch (Exception e) {
                System.out.println("catch 代码块被执行!");
                return 2;
            } finally {
                System.out.println("finally 代码块被执行!");
            }
     
        }
     
    }
  • 相关阅读:
    Java8新特性
    搜索解决方案 -- ElasticSearch入门
    插入排序
    单点登录系统CAS入门
    快速排序
    选择性排序
    冒泡排序
    springcloud入门
    消息中间件 -- RabbitMQ
    ActiveMQ中消息的重发与持久化保存
  • 原文地址:https://www.cnblogs.com/newlangwen/p/12342956.html
Copyright © 2011-2022 走看看