Home > Java > javaTutorial > body text

Common Java array exceptions and solutions

PHPz
Release: 2023-04-22 20:58:06
forward
908 people have browsed it

1. Exception types

The main difference between checked exceptions and unchecked exceptions lies in their handling methods. Checked exceptions need to be processed by the compiler using the try, catch and finally keywords, otherwise a compiler error will occur. This is not necessary for unchecked exceptions. All exceptions in Java classes that inherit Exception are checked exceptions, and all exceptions that inherit RuntimeException are called unchecked exceptions.

2. ClassCastException

Class conversion exception. This exception will be thrown when converting an instance that is not of this class into this class.

If you force a number into a string, this exception will be reported:

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

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

3. NullPointerException

This exception will be thrown when operating the 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());
Copy after login

Tips: Once an exception occurs in the program and is not handled, execution will be terminated.

The above is the detailed content of Common Java array exceptions and solutions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template