java.lang.Throwable
Error通常是灾难性的致命错误,一旦出现这些错误,JVM一般会选择终止线程,影响很大;
Exception通常是可以被程序控制和处理的
try…catch…的作用:如果代码进入到try的错误监控区域并产生catch定义的错误,则输出对应catch代码块的内容
finally (无论是否有异常,总会执行finally代码块)实例
public class Application { public static void main(String[] args) { int a = 1; int b = 0; try { System.out.println("我没错"); System.out.println(a/b); } catch (Error e){ System.out.println("error"); } catch (Exception e){ System.out.println("Exception"); } finally { System.out.println("finally"); } } }ps:
①try下必须有catch,且可以有多个catch;可以没有finally
②catch(想要捕获的异常类型) 多个catch时,异常会按顺序匹配,进入到对应catch代码块中。因此异常类型若有包含关系时,应从小到大排序,例如:
try { System.out.println("我没错"); System.out.println(a/b); } catch (Error e){ System.out.println("error"); } catch (Exception e){ System.out.println("Exception"); } catch (Throwable e){ System.out.println("Throwable"); }
