Java中捕获和抛出异常try/catch/finally
package com.exception; public class Test { public static void main(String[] args) { int a=1; int b=0; try{ new Test().a(); }catch (Error e){ System.out.println("死循环"); }finally { //finally作为善后工作必输出 System.out.println("finally"); } System.out.println("=================="); //快捷键command+option+T try { System.out.println(a/b); } catch (Exception e) { System.out.println("程序出现异常,变量b不能为0"); } finally { System.out.println("finally"); } System.out.println("=================="); try { new Test().b(); } catch (Exception e) { System.out.println("Exception"); } catch (Error e){ System.out.println("Error"); } catch (Throwable e){ System.out.println("Throwable"); //Throwable覆盖面最大,要放最后 } finally { System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } }
输出:
死循环
finally
==================
程序出现异常,变量b不能为0
finally
==================
Error
finally
try/catch/finally快捷键生成:
Mac:command+option+T
Windows:ctrl+alt+T