In-depth checkout of exception types in java array

For exceptions in the program, it is a situation that many programmers do not want to see, because this requires us to query the cause of the exception, and then perform some operations to handle the exception. In Java array operations, there will be some exceptions. Here we have listed two types: ClassCastException and NullPointerException, let's take a look at the specific introduction.

1. Types of abnormalities

The main difference between checked and unchecked exceptions lies in the way they are handled. Checked exceptions need to be handled by the compiler using try, catch and finally keywords, otherwise the compiler will report an error. This is not necessary for unchecked exceptions. All exceptions of classes that inherit Exception in Java are checked exceptions, and all exceptions that inherit RuntimeException are called unchecked exceptions.

2、ClassCastException

Class conversion exception. Converting an instance of this class to this class will throw this exception.

If a number is forcibly converted to a string, this exception will be reported:

Object x = new Integer(0);
System.out.println((String)x);

This is a runtime exception and does not need to be caught manually.

3. NullPointerException

This exception is thrown when manipulating a method or property of a null object.

//情况一:
int[] arr1 = new int[]{1,2,3};
arr1 = null;
System.out.println(arr1[0]);

//情况二:
int[][] arr2 = new int[4][];
System.out.println(arr2[0][0]);

//情况:
String[] arr3 = new String[]{"AA","BB","CC"};
arr3[0] = null;
System.out.println(arr3[0].toString());

Prompt: Once the program is abnormal and has not been dealt with, the execution will be terminated.

Content expansion:

  • Arithmetic exception class: ArithmeticExecption
  • Null pointer exception class: NullPointerException
  • Type casting exception: ClassCastException
  • Array negative subscript exception: NegativeArrayException
  • Array subscript out of bounds exception: ArrayIndexOutOfBoundsException
  • Violation of the safety principle exception: SecturityException
  • File has ended exception: EOFException
  • File not found exception: FileNotFoundException
  • String conversion to number exception: NumberFormatException
  • Operation database exception: SQLException
  • Input and output exception: IOException
  • Method not found exception: NoSuchMethodException

The latest high-frequency interview questions collected in 2021 (all organized into documents), there are a lot of dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations. There are also detailed learning plans and interviews. Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/114541094