java语言中,将程序执行中发生的不正常情况称为"异常"
执行过程中所发生的异常事件可分为两类:
- Error(错误):Java虚拟机无法解决的严重问题.如:JVM系统内部错误,资源耗尽等情况.如此: StackOverflowError[栈溢出]和OOM(out of memory),Error是严重错误,程序会本崩溃
- Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理.例如空指针访问,视图读取不存在的文件,网络连接中断等等,Exception分为两大类:
运行时异常
和编译时异常
.
- 异常分为两大类: 运行时异常和编译时异常
- 运行时异常,编译器不要求强制处理的异常.一般是指编程时的逻辑错误,是程序员应该避免其出现的异常.java.lang.RuntimeException类以及它的子类都是运行时异常
- 运行时异常,可以不作处理,因为这类异常很普遍,若处理可能会对程序的可读性和运行效率产生影响
- 编译时异常,是编译器要求必须处置的异常
常见运行时异常
NullPointerException
当应用程序试图在需要对象的地方使用null时,抛出异常
public class NullPointerExceptionDemo {
public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}
Exception in thread "main" java.lang.NullPointerException
at com.ll.exceptiondemo.NullPointerExceptionDemo.main(NullPointerExceptionDemo.java:10)
ArithmeticException 算数异常
ArrayIndexOutOfBoundException 数组下标越界异常
用非法索引访问数组时抛出异常,如果索引为负或大于等于数组大小,则该索引为非法索引
public class ArrayIndexOutOfBoundsExceptionDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(arr[5]);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at com.ll.enum_.ArrayIndexOutOfBoundsExceptionDemo.main(ArrayIndexOutOfBoundsExceptionDemo.java:10)
ClassCastException 类型转换异常
当试图将对象强制转换为不是实例的子类时,抛出该异常
public class ClassCastExceptionDemo {
public static void main(String[] args) {
// 向上转型
A a = new B();
// 向下转型
B b = (B)a;
// ClassCastException
C c = (C)a;
}
}
class A { }
class B extends A{}
class C extends A{}
NumberFormatException 数字格式异常
当程序试图将字符串转为一种数值类型,但该字符串不能转为适当格式时,则抛出改改异常
public class NumberFormatExceptionDemo {
public static void main(String[] args) {
String name = "ll";
int i = Integer.parseInt(name);
System.out.println(i);
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "ll"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at com.ll.exceptiondemo.NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:10)
编译异常
编译异常指在编译期间,就必须处理的异常,否则代码不能通过编译