异常详述
异常:以不同寻常,非正常。在Java执行时若出现异常,则会导致后续代码均不执行,因此当出现异常时,我们需要解决异常。代码及结果展示:
public class Test1 {
public static void main(String[] args) {
int age = 12;
System.out.println(age);
System.out.println(1/0);
System.out.println(age);
}
}
结果为:
12
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.jd.Test1.Test1.main(Test1.java:8)
//未进行第三行输出
异常的分类(粗略):
在Throwable中分为Exception和Error(其中,Error为jdk的错误,Exception为程序代码出错。)Exception又分为RuntimeException与非RuntimeException。
运行时异常,即RuntimeException及其子类。
检查时异常,即非RuntimeException。
如何区分检查时异常与运行时异常
1、父类
检查时异常:其父类未直接或间接继承RuntimeException。
运行时异常:其父类直接或间接继承RuntimeException。
2、是否需要显式处理
检查时异常:必须需要显式处理。
运行时异常:不需要显式处理。
异常的处理方式
异常的处理方式共分为两类:
1、try-catch-finally
2、throw与throws
try-catch-finally类:
格式:
try {
}catch( ){//对异常的处理
}finally{
}
说明:
1、try用于检查其括号中语句代码是否有异常,若有异常,则进行catch中的操作,若没有,则进行try中的操作;
2、finally中的语句无论如何都会执行;
3、一个try中可以有多项操作,有多个对应分支,顺序由上往下,遵循就近原则;catch括号中所使用的类必须按从小到大书写(catch(Exception)只要出现永远写在最后一项catch分支中)。
public class Test {
public static void main(String[] args) {
int age = 12;
try {
System.out.println(1/2);//可以将2改为0形成运行时异常查看不同的异常执行的语句。
String str = null;
System.out.println(str.length());
Class.forName("asd");//类异常,执行Exception
}catch(ArithmeticException e){//对异常的处理
System.out.println("1"+e);
}catch(NullPointerException e) {
System.out.println("2"+e);
}catch(RuntimeException e) {
System.out.println("3"+e);
}catch(Exception e) {
System.out.println("4"+e);
}finally{//此分支必定执行。
System.out.println(age);
}
}
}