Java从入门到精通 第19章 异常的捕获和处理

本文深入探讨了Java中异常处理的基本概念,包括ArrayIndexOutOfBoundsException的触发条件及处理方式。通过实例展示了try-catch-finally语句块的使用,throws关键字的作用以及如何抛出自定义异常信息。此外,还介绍了如何在方法签名中声明可能抛出的异常类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//数组越界异常处理
public class Test{

    public Test() {
    }
    public static void main(String args[])throws ArrayIndexOutOfBoundsException{
    	int arr[]=new int[5];
    	arr[10]=10;
    	System.out.println("main()方法结束");
    }
}
//result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
	at Test.main(Test.java:14)
//经过处理之后,程序就被会因为异常而中断执行
public class Test{

    public Test() {
    }
    public static void main(String args[]){
    	try{
    		int arr[]=new int[5];
    		arr[10]=10;
    	}catch(ArrayIndexOutOfBoundsException ex){
    		ex.printStackTrace();
    	}finally{
    		System.out.println("这里一定会被执行");
    	}
    	System.out.println("main()方法结束");
    }
}
//throws关键字
public class Test{

    public Test() {
    }
    public static void main(String args[]){
    	int arr[]=new int[5];
    	try{
    		setZero(arr,10);
    	}catch(ArrayIndexOutOfBoundsException e){
    		e.printStackTrace();
    	}
    	System.out.println("main 方法结束");
    }
    public static void setZero(int arr[],int index)
    throws ArrayIndexOutOfBoundsException
    {
    	arr[index]=0;
    }
}
//result:
java.lang.ArrayIndexOutOfBoundsException: 10
	at Test.setZero(Test.java:24)
	at Test.main(Test.java:15)
main 方法结束
//throw关键字
public class Test{
    public Test() {
    }
    public static void main(String args[])throws ArrayIndexOutOfBoundsException{
    	try{
    		throw new ArrayIndexOutOfBoundsException("\n我是个性化的异常信息:\n数组下标越界");
    	}catch(ArrayIndexOutOfBoundsException ex){
    		System.out.println(ex);
    	}
    }
}
//有些显得无事找事
//关键字throws和throw的配合使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值