try...catch...finally的使用和执行情况

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/83349853

try…catch…finally

  1. 执行顺序:
    try代码块中出现异常后,会被catch捕获,转而执行catch代码块,最后执行finally代码块

  2. 各代码块里的执行情况

    try代码块—在try{}中,异常后面的代码不执行—(全部执行或部分执行)
    catch代码块—try{}没异常,catch不执行。try有异常,catch执行(全部执行或不执行)
    finally代码块—永远执行(绝对全部执行)

以下两段代码实现效果一样
try…catch

package com.exception.test;

import java.util.Scanner;

public class TryCatch {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a,b,c;
        try {
            a=sc.nextInt();
            b=sc.nextInt();
            c=a%b;
            System.out.println("余数为:"+c);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("程序继续执行");
    }
}

try…catch…finally

package com.exception.test;

import java.util.Scanner;

public class TryCatch {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a,b,c;
        try {
            a=sc.nextInt();
            b=sc.nextInt();
            c=a%b;
            System.out.println("余数为:"+c);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("程序继续执行");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hju22/article/details/83349853