try catch 捕获处理异常

try{}
catch(Exception e){}
finally{}

package com.xiaohu.entity;

import java.util.Scanner;

public class Test1 {
    public static void main(String[] args) {
        Scanner sa = new Scanner(System.in);
        int n1 = sa.nextInt();
        int n2 = sa.nextInt();
        
        try {
            int res =  n1/n2;
            System.out.println("res:"+res);
        }catch(Exception e) {
            System.out.println(e);
        }finally {
            System.out.println("不管怎样都会执行");
        }
    }
}

抛出异常

throws Exception

package com.xiaohu.entity;

public class Test2 {
    public int getRes(int x, int y) throws Exception {
        int t = 0;
        t = x/y;
        return t;
    }
    public int getM(int a, int b){
        int t = 0;
        
        try {
            t = 100+getRes(a,b);
        }catch(Exception e){
            System.out.println("error!");
        }
        
        return t;
    }
    public static void main(String[] args) {
        Test2 t = new Test2();
        int res = t.getM(10, 1);
        System.out.println(res);
    }
}

异常执行顺序

先子类 后父类 Exception 在最后

package com.xiaohu.test;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Test5 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            System.out.println("请输入第一个数");
            int num1 = sc.nextInt();
            System.out.println("请输入第二个数");
            int num2 = sc.nextInt();
            
            try {
                int res = num1/num2;
                System.out.println("res:"+res);
            }catch(ArithmeticException e) {
                System.out.println("除数为零!error");
            }
            
        }catch(InputMismatchException e) {
            System.out.println("您输入的值不是数值类型");
        }
    }
}
package com.xiaohu.test;

public class Test1 {
    public static void main(String[] args) {
        int[] x = {1,2,3,4,5,6};
        int len = x.length;
        try {

            int y = x[x.length];
            System.out.println(y);
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
        }
        
    }
}
最后修改:2024 年 10 月 21 日
如果觉得我的文章对你有用,请随意赞赏