当前位置:   article > 正文

【JavaSE】 try-catch 异常处理_java的try catch处理异常

java的try catch处理异常

try-catch 异常处理

1. try-catch 方式处理异常说明

  1. Java提供try和catch块来处理异常。try块用于包含可能出错的代码。catch块用
    于处理try块中发生的异常。可以根据需要在程序中有多个try…catch块。
  2. 基本语法
	try {
	//可疑代码
	//将异常生成对应的异常对象,传递给catch块
	}catch(异常){
	//对异常的处理
	}
	//如果没有finally,语法是可以通过
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. try-catch 方式处理异常-快速入门

	public static void main(String[] args) {
	       int num1 = 10;
	       int num2 = 0;
	   try {
	       int res = num1 / num2;
	   } catch (Exception e) {
	       System.out.println("出现异常的原因=" + e.getMessage());//输出异常信息
	   }	
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3. try-catch 方式处理异常-注意事项

快速调出try-catch :选中代码 Ctrl+Alt+t

  1. 如果异常发生了,则异常发生后面的代码不会执行,直接进入到catch块.
public static void main(String[] args) {
        try {
            String str = "兮动人";
            int a = Integer.parseInt(str);
            System.out.println("数字" + a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息:" + e.getMessage());
        }

        System.out.println("程序继续执行...");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

  1. 如果异常没有发生,则顺序执行try的代码块,不会进入到catch.
public static void main(String[] args) {
        try {
            String str = "123";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息:" + e.getMessage());
        }

        System.out.println("程序继续执行...");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

  1. 如果希望不管是否发生异常,都执行某段代码 (比如关闭连接,释放资源等)
    则使用如下代码 - finally { }
try{
	//可疑代码
}catch(异常){
	//...
}finally{
	//释放资源 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 无异常情况下:
public static void main(String[] args) {
        try {
            String str = "123";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息:" + e.getMessage());
        } finally {
            System.out.println("finally代码被执行...");
        }

        System.out.println("程序继续执行...");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在这里插入图片描述

  • 有异常情况下:
public static void main(String[] args) {
        try {
            String str = "兮动人";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息:" + e.getMessage());
        } finally {
            System.out.println("finally代码被执行...");
        }

        System.out.println("程序继续执行...");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在这里插入图片描述

  1. 可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,比如(Exception在后,NullPointerException在前),如果发生异常,只会匹配一个catch,案例演示:
  • 分别对NullPointerExceptionArithmeticException 异常进行分开捕获
public class TryCatchDetail02 {
    public static void main(String[] args) {

        //1.如果代码块可能有多个异常
        //2.可以使用多个catch分别捕获,相应处理
        //3.要求之类异常写在前面,父类异常写在后面
        try {
            Person person = new Person();
            person = null;
            System.out.println(person.getName()); //NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;//
        } catch (NullPointerException e) {
            System.out.println("空指针异常:" + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("算术异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {

        }
    }
}

class Person {
    private String name = "xdr";

    public String getName() {
        return name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

在这里插入图片描述

  • 当去掉 person = null;
    在这里插入图片描述
  1. 可以进行try-finally配合使用,这种用法相当于没有捕获异常,因此程序会直接崩掉/退出应用场景:就是执行一段代码,不管是否发生异常,都必须执行某个业务逻辑。
try{
	//代码
}finally{
	//总是执行
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 没有catch,默认是使用 throws 来捕获异常
public class TryCatchDetail03 {
    public static void main(String[] args) {
        try {
            int n1 = 10;
            int n2 = 0;
            System.out.println(n1 / n2);
        }finally {
            System.out.println("执行finally...");
        }
        System.out.println("程序继续执行...");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在这里插入图片描述

4. try-catch 异常处理练习

  1. 看看输出什么?

分析:数组并没有给赋值,所以都为 null ,这时候就报 空指针异常,被 catch 捕获(此时返回3),但 finally 最后还是要执行的,所以 返回 4

public class TryCatchExercise01 {
    public static int method() {
        try {
            String[] names = new String[3];//String[]数组
            if (names[1].equals("tom")) {//NullPointerException
                System.out.println(names[1]);
            } else {
                names[3] = "xdr";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            return 2;
        } catch (NullPointerException e) {//捕获
            return 3;
        } finally { //必须执行
            return 4; //返回4
        }
    }

    public static void main(String[] args) {
        System.out.println(method()); //4
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

在这里插入图片描述

  1. 在上面的基础上,加个 i 的变化
public class TryCatchExercise02 {public static int method() {
    int i = 1;
    try {
        i++; //i = 2
        String[] names = new String[3];
        if (names[1].equals("tom")) {//空指针
            System.out.println(names[1]);
        } else {
            names[3] = "xdr";
        }
        return 1;
    } catch (ArrayIndexOutOfBoundsException e) {
        return 2;
    } catch (NullPointerException e) {
        return ++i; //i = 3
    } finally {//必须执行
        return ++i; //i = 4
    }
}

    public static void main(String[] args) {
        System.out.println(method());
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

在这里插入图片描述

  1. 当执行到空指针异常被 catch 捕获后,没有立即返回 3,而是继续执行 finally 里的代码,这时候 finally 里的 i = 4 输出后,才执行 return 3
public class TryCatchExercise03 {
    public static int method() {
        int i = 1;//i = 1
        try {
            i++;// i=2
            String[] names = new String[3];
            if (names[1].equals("tom")) { //空指针
                System.out.println(names[1]);
            } else {
                names[3] = "xdr";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            return 2;
        } catch (NullPointerException e) {
            return ++i;  // i = 3 => 保存临时变量 temp = 3;
        } finally {
            ++i; //i = 4
            System.out.println("i=" + i);// i = 4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());// 3
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

在这里插入图片描述

5. try-catch-finally 执行顺序小节

  1. 如果没有出现异常,则执行try块中所有语句,不执行catch块中语句,如果有finally,最后还需要执行finally里面的语句
  2. 如果出现异常,则try块中异常发生后,try块剩下的语句不再执行。将执行catch块中的语句,如果有finally,最后还需要执行finally里面的语句

6. 练习题:利用异常来判断输入的类型

如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止

思路
1. 创建Scanner对象
2. 使用无限循环,去接收一个输入
3. 然后将该输入的值,转成一个int
4. 如果在转换时,抛出异常,说明输入的内容不是一个可以转成int的内容
5. 如果没有抛出异常,则break 该循环
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
public class TryCatchExercise04 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        String inputStr = "";
        while (true) {

            System.out.println("请输入一个整数:"); 
            inputStr = scanner.next();
            try {
                num = Integer.parseInt(inputStr); //这里可能抛出异常
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的不是一个整数:");
            }
        }

        System.out.println("你输入的值是=" + num);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 输入一个整数:
    在这里插入图片描述

  • 输入一个非整数就会一直提示,直到你输入一个整数才会结束循环
    在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/252901
推荐阅读
相关标签
  

闽ICP备14008679号