English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Что произойдет, если исключения не обрабатываются в программе Java?

An exception is a problem that occurs during program execution (runtime error). To understand the purpose, let's look at it in a different way.

通常,在编译程序时,如果没有创建.class文件,则该文件是Java中的可执行文件,并且每次执行此.classWhen running the program, it should run successfully to execute each line in the program without any problems. However, in some special cases, the JVM encounters some ambiguous situations during program execution, that is, it does not know what to do.

Here are some example scenarios-

  • If your array size is 10, then a line in the code tries to access the 11th element of the array.

  • If you try to divide a number by 0 (the result is infinite, and the JVM cannot understand how to evaluate it).

This situation is called an exception. Each possible exception is represented by a predefined class, and you can find all exception classes in the java.lang package. You can also define your own exceptions.

Some exceptions are reported at compile time and are called compile-time exceptions or checked exceptions.

When such exceptions occur, you need to handle them using try-catch blocks or throw them using the throws keyword (defer the handling).

If you do not handle exceptions

If an exception occurs and is not handled, the program will terminate abruptly, and the code after the line that caused the exception will not be executed.

Example

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

An exception is raised whenever a –ve value or a value greater than or equal to the size of the array is used.ArrayIndexOutOfBoundsException.

For example, if you execute the following code, it will display the elements of the array and ask you to provide an index to select an element. Since the size of the array is 7, the valid indices are 0 to 6.

Example

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("Элементы в массиве: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Введите индекс требуемого элемента: ");
      int element = sc.nextInt();
      System.out.println("Элемент в данном индексе: :: " + myArray[element]);
   }
}

However, if you observe the following output, we have requested the element at index 9, because it is an invalid index, and therefore it causedArrayIndexOutOfBoundsExceptionand terminated the execution.

Runtime exception

Элементы в массиве:
[897, 56, 78, 90, 12, 123, 75]
Введите индекс требуемого элемента:
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("Элементы в массиве: ");
      System.out.println(Arrays.toString(myArray));
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Введите индекс требуемого элемента: ");
         int element = sc.nextInt();
         System.out.println("Элемент в данном индексе: :: " + myArray[element]);
      }
         System.out.println("Пожалуйста, введите правильный индекс (0 до 6)");
      }
   }
}

Результат вывода

Элементы в массиве:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
Введите индекс требуемого элемента:
7
Пожалуйста, введите правильный индекс (0 до 6)
Основной учебник
Скорее всего, вам понравится