try { //try:监控区域 }catch ( 想要捕获的异常类型){ //如果监控区域出现了ArithmeticException这个异常就执行这个 }
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("程序出现异常,b不能为0" );//如果监控区域出现了ArithmeticException这个异常就执行这个 }finally { System.out.println("finally"); } } }
运行结果
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 { System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } }
try { }catch (Error e){ System.out.println("程序出现异常 Error" ); }catch (Exception e){ System.out.println("程序出现异常 Exception" ); }catch (Throwable e){ System.out.println("程序出现异常 Throwable" ); } finally { System.out.println("finally"); }
try { System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); //打印错误的栈信息 } finally { }
public class Test { public static void main(String[] args) { int a = 1; int b = 0; try { if (b == 0){ throw new ArithmeticException(); //主动抛出异常 } System.out.println(a/b); }catch (Throwable e){ System.out.println("程序出现异常 Throwable" ); } finally { System.out.println("finally"); } }