java中程序发生异常如何处理_如果未在Java程序中处理异常,会发生什么情况?...

例外是程序执行期间发生的问题(运行时错误)。为了理解目的,让我们以不同的方式来看待它。

通常,在编译程序时,如果编译时没有创建.class文件,则该文件是Java中的可执行文件,并且每次执行此.class文件时,它都应成功运行以执行程序中的每一行没有任何问题。但是,在某些特殊情况下,JVM在执行程序时会遇到一些模棱两可的情况,即不知道该怎么做。

这是一些示例方案-如果您的数组大小为10,则代码中的一行尝试访问该数组中的第11元素。

如果您试图将数字除以0(结果为无穷大,并且JVM无法理解如何对其求值)。

这种情况称为例外。每个可能的异常都由预定义的类表示,您可以在java.lang包中找到所有异常类。您也可以定义自己的异常。

某些异常是在编译时提示的,称为编译时异常或已检查的异常。

当发生此类异常时,您需要使用try-catch块来处理它们,或者使用throws关键字将它们抛出(推迟处理)。

如果您不处理异常

发生异常时,如果不处理,程序将突然终止,并且导致异常的行之后的代码也不会执行。

示例

通常,数组的大小固定,并且使用索引访问每个元素。例如,我们创建了一个大小为7的数组。然后,用于访问该数组元素的有效表达式将为a [0]至a [6](长度为1)。

每当使用–ve值或大于或等于数组大小的值时,就会引发ArrayIndexOutOfBoundsException。

例如,如果执行以下代码,它将显示数组中的元素,并要求您提供索引以选择一个元素。由于数组的大小为7,因此有效索引为0到6。

示例import java.util.Arrays;

import java.util.Scanner;

public class AIOBSample {

public static void main(String args[]){

int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};

System.out.println("Elements in the array are: ");

System.out.println(Arrays.toString(myArray));

Scanner sc = new Scanner(System.in);

System.out.println("Enter the index of the required element: ");

int element = sc.nextInt();

System.out.println("Element in the given index is :: "+myArray[element]);

}

}

但是,如果您观察到以下输出,则我们已请求索引为9的元素,因为它是无效索引,因此引发了ArrayIndexOutOfBoundsException并终止了执行。

运行时异常Elements in the array are:

[897, 56, 78, 90, 12, 123, 75]

Enter the index of the required element:

7

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7

at AIOBSample.main(AIOBSample.java:12)

要解决此问题,您需要通过在try-catch块中包装负责该异常的代码来处理该异常。import java.util.Arrays;

import java.util.Scanner;

public class AIOBSample {

public static void main(String args[]){

int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};

System.out.println("Elements in the array are: ");

System.out.println(Arrays.toString(myArray));

try {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the index of the required element: ");

int element = sc.nextInt();

System.out.println("Element in the given index is :: "+myArray[element]);

}catch(ArrayIndexOutOfBoundsException ex) {

System.out.println("Please enter the valid index (0 to 6)");

}

}

}

输出结果Elements in the array are:

[1254, 1458, 5687, 1457, 4554, 5445, 7524]

Enter the index of the required element:

7

Please enter the valid index (0 to 6)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值