十六、Java异常
异常处理使得程序可以处理非预期的情景,并进行正确的处理。
异常分为两种;
1.编写异常。
eg:
定义一个整型,结果赋值一个double类型的数,代码编译器就会用红线表示。
2.运行时异常
eg1:
程序需要输入一个整数而用户输入一个double值,会得到InputMismatchException的异常。
eg2:
ArrayIndexOutOfBoundsException:数组下标越界异常。
异常类型
捕捉异常
1.在方法中可以使用try和catch关键字来捕捉异常。
语法:
try {
} catch (Exception e) {
// TODO: handle exception
}
eg:
2.多个try块
语法:
try {
} catch (ExceptionType1 e) {
// TODO: handle exception
} catch (ExceptionType2 e2) {
// TODO: handle exception
} catch (ExceptionType3 e3) {
// TODO: handle exception
}
ag:
Test.java
package Hcybx;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入整数1");
int num1 = input.nextInt();
System.out.println("请输入整数2");
int num2 = input.nextInt();
int[] array = new int[5];
try {
int result = num1/num2;
array[num2]=num1;
System.out.println("请输入你的年龄:");
int age = input.nextInt();
} catch (ArithmeticException e) {
System.out.println("算数异常!");
} catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("数组下标越界异常!");
} catch (InputMismatchException e3) {
System.out.println("运行时异常!");
}
}
}
运行结果:
try-finally块
定义:将异常向外抛出,自己不处理。
语法:
try {
} catch (ExceptionType1 e) {
// TODO: handle exception
} catch (ExceptionType2 e2) {
// TODO: handle exception
} catch (ExceptionType3 e3) {
// TODO: handle exception
} finally {
}
finally块在try块或catch块之后。无论受保护的代码块是否发生异常,最终都会执行finally块中的代码。
throws/throw关键字
自定义异常
步骤:
1.创建自定义异常类。
2. 在方法中通过throw关键字抛出异常对象。
3. 使用try-catch语句并捕获处理。
4. 在出现异常方法中处理异常。
eg: