异常
-
Exception (可以通过程序解决的异常)
-
运行时异常( RuntimeException):运行后报错
-
编译时异常:编译时代码标红
-
Error(处理起来比较麻烦不希望处理)
Exception 和 Error 都属于unchecked,除了这两种其他都是checked
处理异常
关键字:throws,try,catch,finally,throw
-
throw: 人为抛异常 throw 异常对象(throwable及其子类)
-
throws:抛出异常,发生异常后不处理,直接抛给上层上层调用处;方法头使用throws声明这个方法可能会抛出的异常
public class List {
Object[] obj;
int index;
int size;
public List() throws Exception{}
public Object get(int index)throws RuntimeException {
if(index <0 || index >= size) {
throw new RuntimeException(index + "下标越界");
}
return obj[index];
}
}
class A extends List {
public A() throws Exception{
super();
}
public Object get(int index) throws RuntimeException{
return null;
}
}
-
try-catch:处理异常
try块中放置我们可能出现的异常的;
try可以有多个catch匹配,从上到下进行匹配,将异常范围大的放到后边;
当try块异常被处理后,整个try-catch结束;
try块中代码尽量少;
-
finally:结合try使用,表示无论有无异常都要执行
public class Demo02 {
public static void main(String[] args) { //输出结果 异常 end 0
int res = value();
System.out.println(res);
}
public static int value(){ //异常 end 0
try{
int a = 3/0;
return 1;
}catch (Exception ex){
System.out.println("异常");
return -1;
}finally {
System.out.println("end");
return 0;
}
}
}
其中throw,throws属于抛出异常,finally属于处理异常
如果程序的异常得到处理,程序会继续执行。如果没有处理程序会终止运行。
t
ry/catch/finally
结构中必须要有try(相当于皇帝),catch(相当于太监)可以有多个,finally(相当于皇后)只能有一个,结合try出现;
try-catch ,try-catch....,try-finally 允许的结构
public class Demo01 {
public static void main(String[] args) { // 输出结果 3 end
try{
int n = 3/1;
System.out.println(n);
}catch(ArithmeticException ex){
System.out.println("运算异常");
}catch(Exception ex2){
System.out.println("异常");
}finally {
System.out.println("end");
}
}
}