java第十九次学习笔记

java第十九次学习笔记


前言

斯人若彩虹遇上方知有

一、try catch

package Demo01;

import java.io.IOException;
/*
 * 1.如果try 中出现了多个异常对象,那么可以使用多个catch 来进行异常处理
 * 
 * 2.如果try中产生了异常,那么就会执行catch中的异常处理逻辑,执行完catch中的逻辑会继续执行try--catch
 *   如果try中没有产生异常,那么就不会执行catch中的异常逻辑,直接执行后续代码
 *   
 *   finally关键字
 *   1.不能单独使用,必须与try一起使用
 *   2.一般用于资源释放(资源回收),无论程序是否出现异常,都要释放资源(I/o)
 * 
 * 
 * 
 * 
 */
public abstract class Demo01TryCatch {
    
    
	public static void main(String[] args) {
    
    
		try {
    
    
			readFile("D:\\a.");
		} catch (IOException e) {
    
    
			
			//e.printStackTrace();
			//System.out.println("catch 文件后缀发生错误");
			//System.out.println(e.getMessage());返回简短的异常消息
			//System.out.println(e.toString());返回详细的异常消息包含了异常类型
			//System.out.println(e);
			
			e.printStackTrace();
			
			
			
		}finally {
    
    
			System.out.println("资源释放");
		} 
		System.out.println("后续代码");
	}
	public static void readFile(String fileName) throws IOException{
    
    
		
		if(!fileName.endsWith(".txt")) {
    
    
			throw new IOException("五班代码文件后缀名不对");
			
		}
		System.out.println("没有发生异常");
	}

}

在这里插入图片描述

二、多个异常如何处理

package Demo01;

import java.util.List;

/*多个异常如何处理
 * 1.多个异常分别处理
 * 2.多个异常一次捕获,多次处理
 * 3.多个异常一次捕获,一次处理
 * 
 */
public class Demo02Exception {
    
    
	public static void main(String[] args) {
    
    
		/*try{
			int[] arr= {1,2,3};
			System.out.println(arr[3]);
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println(e);
		}
		try{
		    List<Integer> List= List.of(1,2,3);
			System.out.println(List.get(3));
		
		}catch(IndexOutOfBoundsException e){
			System.out.println(e);
		}	
		
		
		try {
			int[] arr1=null;
			int[] arr= {1,2,3};
			List<Integer> List= List.of(1,2,3);
			System.out.println(List.get(3));
		}catch(ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
		}catch(IndexOutOfBoundsException e){
			e.printStackTrace();
		}catch(NullPointerException e) {
			e.printStackTrace();
		}*/
		try {
    
    
			
			int[] arr1=null;
			int[] arr= {
    
    1,2,3};
			List<Integer> list= List.of(1,2,3);
			System.out.println(list.get(3));
		}catch(Exception e) {
    
    
			e.printStackTrace();
		}
		
		
	}

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_54405545/article/details/116769423