当应用程序试图在需要对象的地方使用null时,抛出该异常。
package com.javaException;
public class JavaNullPointerException {
public static void main(String[] args) {
String s = null;
System.out.println(s.length()); //这里就相当于null.length()所以会抛出空指针异常
}
}
Exception in thread "main" java.lang.NullPointerException
at com.javaException.JavaNullPointerException.main(JavaNullPointerException.java:6)
当出现异常的运算条件时,抛出此异常。例如:一个整数“除以零”时,抛出该异常。
package com.javaException;
public class JavaArithmeticException {
public static void main(String[] args) {
System.out.println(10 / 0);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.javaException.JavaArithmeticException.main(JavaArithmeticException.java:5)
用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。
package com.javaException;
public class JavaArrayIndexOutOfBoundsException {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
System.out.println(arr[4]);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.javaException.JavaArrayIndexOutOfBoundsException.main(JavaArrayIndexOutOfBoundsException.java:6)
当试图将对象强制转换为不是实例的子类时,抛出该异常。
package com.javaException;
public class JavaClassCastException {
public static void main(String[] args) {
A b = new B();
C c = (C)b;
}
}
class A{
}
class B extends A{
}
class C extends A{
}
Exception in thread "main" java.lang.ClassCastException: com.javaException.B cannot be cast to com.javaException.C
at com.javaException.JavaClassCastException.main(JavaClassCastException.java:6)
当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。用这种异常,我们可以确保输入是满足条件数字。
package com.javaException;
public class JavaNumberFormatException {
public static void main(String[] args) {
String str = "abc";
int i = Integer.parseInt(str);
System.out.println(i);
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javaException.JavaNumberFormatException.main(JavaNumberFormatException.java:7)
编译异常是指在编译期间,就必须处理的异常,否则代码不能通过编译。
注:
如果程序员没有显示的用try-catch-finally或throws,程序默认使用的时throws来抛出异常。
try{
//可疑代码
//将异常生成对应的异常对象,传递给catch块
}catch(异常){
//对异常的处理
}
try{
...
}catch(NullPointerException e){
...
}catch(Exception e){
...
}finally{
...
}
package com.javaException;
public class JavaCustomException {
public static void main(String[] args) {
int age = 200;
if(!(age >= 1 && age <= 160)){
throw new AgeException("The age is error");
}
}
}
class AgeException extends RuntimeException{
public AgeException(String message) {
super(message);
}
}
Exception in thread "main" com.javaException.AgeException: The age is error
at com.javaException.JavaCustomException.main(JavaCustomException.java:7)