java runtime 异常_java 中怎么处理 RuntimeException 异常

运行时异常或未检查的异常是在执行时发生的异常。其中包括编程错误,例如逻辑错误或 API 使用不当。运行时异常在编译时被忽略。

IndexOutOfBoundsException,ArithmeticException,ArrayStoreException和ClassCastException 是运行时异常的示例。

示例

在下面的Java程序中,我们有一个大小为5的数组,并且试图访问第6个元素,这将抛出异常 ArrayIndexOutOfBoundsException。public class ExceptionExample {

public static void main(String[] args) {

//创建大小为5的整数数组

int inpuArray[] = new int[5];

//填充数组

inpuArray[0] = 41;

inpuArray[1] = 98;

inpuArray[2] = 43;

inpuArray[3] = 26;

inpuArray[4] = 79;

//访问大于数组大小的索引

System.out.println( inpuArray[6]);

}

}

运行时异常Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

at MyPackage.ExceptionExample.main(ExceptionExample.java:14)

处理运行时异常

您可以处理运行时异常并避免异常终止,但是Java中没有针对运行时异常的特定修复程序,具体取决于异常,所需更改代码的类型。

例如,如果您需要在上面列出的第一个程序中修复 ArrayIndexOutOfBoundsException,则需要删除/更改访问数组索引位置超出其大小的行。public class ExceptionExample {

public static void main(String[] args) {

//创建大小为5的整数数组

int inpuArray[] = new int[5];

//Populating the array

inpuArray[0] = 41;

inpuArray[1] = 98;

inpuArray[2] = 43;

inpuArray[3] = 26;

inpuArray[4] = 79;

//访问大于数组大小的索引

System.out.println( inpuArray[3]);

}

}

输出结果26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值