Home  >  Article  >  Java  >  What are the common exceptions in java

What are the common exceptions in java

王林
王林Original
2019-11-13 15:11:572770browse

What are the common exceptions in java

##1.NullPointerException: Null pointer exception

Example:

public static void main(String[] args) {
String str = null;
//此处报空指针异常
System.out.println(str.length());
}

The exception information output by the console is:

Exception in thread "main" java.lang.NullPointerException
at cn.com.gjw.MyClass.main(MyClass.java:7)

2.ClassCastException: Type cast exception

Example:

public static void main(String[] args) {
// 类型强制转换异常
Object x = new String("String");
System.out.println((Integer) x);
}

The exception information output by the console is:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at cn.com.gjw.MyClass.main(MyClass.java:7)

3.ArrayIndexOutOfBoundsException: Array subscript out-of-bounds exception

Example:

public static void main(String[] args) {
int arr[] = {1,2};
// 此处报数组下标越界异常
System.out.println(arr[2]);
}

The exception information output by the console is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at cn.com.gjw.MyClass.main(MyClass.java:7)

4.ArithmeticException : Arithmetic operation exception

Example:

public static void main(String[] args) {
// 整数0做了分母,报算术运算异常
System.out.println(1 / 0);
}

The exception information output by the console is:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at cn.com.gjw.MyClass.main(MyClass.java:6)

5.NumberFormatException: Number format exception

Example:

public static void main(String[] args) {
// 将字符串“it”转换为Integer类型的,当然会报数字格式异常啦
System.out.println(Integer.parseInt("it"));
}

The exception information output by the console is:

Exception in thread "main" java.lang.NumberFormatException: For input string: "it"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at cn.com.gjw.MyClass.main(MyClass.java:6)

Recommended tutorial:

Java tutorial

The above is the detailed content of What are the common exceptions in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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