异常的简介
异常的定义
运行期间出现的错误,而不是编译时的语法错误
例如:
打开一个不存在的文件
网络连接中断
操作数组越界等
异常类的继承关系
异常类的重点
下面通过一个例子看一下
编写一个方法,比较两个字符串。假如其中一个字符串为空,会产生NullPointerException异常,在方法声明中通告该异常,并在适当时候触发异常,然后编写一个程序捕获该异常
public class Test {
public static void test(String a,String b) throws NullPointerException{
if(a==null||b == null) {
throw new NullPointerException();
}
}
public static void main(String[] args) {
try{
String a = null;
String b= "hello";
test(a,b);
}catch(NullPointerException e){
e.printStackTrace();
}
}
}
运行结果如下
这样就捕捉到了异常
以上通过课堂笔记整理