异常的捕获处理——try{} catch(){}
如果一个异常不去处理,会导致程序无法编译或运行
异常捕获:
try{
写可能出现异常的代码;
}
catch(异常类型 标识符){
如果try中的代码出现了异常,并且异常类型和catch的异常的类型可以匹配上,就会执行这里的逻辑
}
//如果有多个异常,要保证父类异常在后(运行时异常:RuntimeException),子类异常在前(数组下标越界异常:ArrayIndexOutOfBoundsException)
//异常的捕获处理try{} catch(){}
public class ExceptionTest1 {
public static void main(String[] args) {
//先写一个可能出现异常的代码
/* int[] array = {1,2,3,4,5};
int ele = array[5];*/
//然后把代码放到try中
try {
//如果在try结构中,出现了异常,那么从异常出现的位置开始,往后的所有代码将不再执行了
int[] array = {1,2,3,4,5};
int ele = array[5];
}
//这里的变量e前面的类型必须和错误的形式一致,否则将会报错
catch (ArrayIndexOutOfBoundsException e){
System.out.println("一个数组下标越界异常被捕获处理了");
}
//一个异常如果被捕获处理了,那么将不再影响程序的执行
System.out.println("end");
}
//多个异常进行处理try{} catch(){}catch(){}
import java.util.Scanner;
public class ExceptionHandler {
public static void main(String[] args) {
multpleCatch();
}
private static void multpleCatch() {
try {
//如果用户输入的值为0,就会出现异常(这个是算术异常)
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int ret = 10 / number;
//数组下表越界异常
int[] array = {1,2,3,4,5};
System.out.println(array[5]);
}catch (ArithmeticException e){
System.out.println("出现了算术异常");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("出现了数组下标越界异常");
}
}
}
//也可以将两种异常放在一个地方输出
import java.util.Scanner;
public class ExceptionHandler {
public static void main(String[] args) {
multpleCatch();
}
private static void multpleCatch() {
try {
//如果用户输入的值为0,就会出现异常(这个是算术异常)
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int ret = 10 / number;
//数组下表越界异常
int[] array = {1,2,3,4,5};
System.out.println(array[5]);
}catch (ArithmeticException | ArrayIndexOutOfBoundsException e ){
//这里的或只能写一个|,不能写两个||(逻辑或),两 个||是需要boolean类型的值,而这里不是值,是类型。
System.out.println("出现了算术异常或者数组下标越界异常");
}catch (RuntimeException e){
System.out.println("出现了其他运行异常");
}
}
}
//finally字句的使用
//常常在finally中进行资源释放,流的关闭等操作
public class ExceptionHandler {
public static void main(String[] args) {
multpleCatch();
}
private static void multpleCatch() {
try {
//数组下表越界异常
int[] array = {1,2,3,4,5};
System.out.println(array[5]);
}catch (ArrayIndexOutOfBoundsException e ){
System.out.println("出现了数组下标越界异常");
}finally {
//无论try中的代码有没有执行,即使出现终止了,也会执行finally中的代码
System.out.println("finally中的代码执行了");
}
}
}