异常:指程序在运行时出现错误而通知调用者的一种机制。
运行时:指程序已经编译通过得到class文件,由JVM执行过程中出现的错误。
像把System.out.println编写错误,其在编译过程中就会出现错误,这样的错误属于“编译器”错误,与异常是不一样的。
平时的代码练习中出现的一些异常:
1.数组下标越界:
int[] arr = new int[]{1,2,3};
System.out.println(arr[3]);
//执行结果为
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
2.除法运算时除以0:
System.out.println(10 / 0);
//执行结果
//Exception in thread "main" java.lang.ArithmeticException: / by zero
3.访问null对象
public class Test2 {
public int num = 5;
public static void main(String[] args) {
Test2 T = null;
System.out.println(T.num);
}
//执行结果
//Exception in thread "main" java.lang.NullPointerException
异常的基本用法
基本语法:
try{
有可能出现异常的语句...
} catch(异常类型 异常对象 ) {
出现异常后的处理行为....
} finally {
异常的出口
}
注:
1.try带码块中放的是可能出现异常的代码
2.catch里放的是出现异常后的处理行为
3.finally里面的代码是最后执行且一定会被执行的
4.其中catch和finally可有可无