异常处理(狂神)
-
Error(错误)
-
Arithmetic(算术异常)
-
exception(异常)
-
throwable(可划异常)–通过源码throwable是exception的类
抛出异常:ctrl+alt+t
执行异常顺序时多为:从1-4依次捕获(由2-4范围逐渐增幅),error放首位防止出现致命错误
error:程序出现问题本身无法恢复,让程序终止(栈溢出等)
package exception;
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
try { //try监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ //捕获异常
System.out.println("分母不为零");
}finally { //善后工作(非必须)
System.out.println("finally");
}
}
}
//catch (ArithmeticException e)->catch(想要捕捉的异常类型){}
5.主动异常
package exception;
public class text2 {
public static void main(String[] args) {
int a=1;
int b=0;
try { //try监控区域
if (b==0) {
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}catch (Error e){
System.out.println("Error");
}catch (ArithmeticException e) {
System.out.println("分母不为零");
}catch (Exception e) {
System.out.println("Exception");
}catch (Throwable t) {
System.out.println("Throwable");
} finally {
System.out.println("finally");
}
}
}