try/catch/finally的知识

首先try/catch/finally字句,是Java为异常处理提供的关键字。try块包含可能产生异常的语句或者异常发生时不应该执行的语句。try块后至少跟着一个catch子句来处理异常,或者一条finally子句(也可以不跟该子句)。每个catch子句在异常参数中指定要处理的异常类型。如果有finally子句则无论如何都会执行该finally子句的代码。

抛出点:也就是异常发生的地方。

异常处理的终止模型:如果某个try块发生了异常,在该try块立即终止执行,并且将程序的控制转移到try块后面的第一个catch子句。

public class TestTryCatchFinally { public static void throwException () throws Exception{ try{ System.out.println("Method throwException"); throw new Exception(); } catch (Exception exception){ System.out.println("Exception handled in method throwException"); throw exception; } finally{ System.out.println("Finally executed in throwException"); } } public static void doesNotThrowException(){ try{ System.out.println("Method doesNotThrowException"); } catch (Exception exception){ System.err.println(exception); } finally{ System.out.println("Finally executed in doesNotThrowException"); } System.out.println("End of method doesNotThrowException"); } public static void main (String args[]){ try{ throwException(); System.out.println("This text will not be printed."); } catch (Exception exception){ System.out.println("Exception handled in main"); } doesNotThrowException(); } }

输出:

Method throwException Exception handled in method throwException Finally executed in throwException Exception handled in main Method doesNotThrowException Finally executed in doesNotThrowException End of method doesNotThrowException

Java2的平台中提供了链式异常,使得异常对象能够维护完整的堆栈记录信息,下面这段代码可以看清楚链式异常是如何工作的。

public class UsingChainedExceptions{ public static void method1 () throws Exception{ try{ method2(); } catch (Exception exception){ throw new Exception("Exception thrown in method1", exception); } } public static void method2() throws Exception{ try{ method3(); } catch(Exception exception){ throw new Exception ("Exception thrown in method2", exception); } } public static void method3() throws Exception { throw new Exception ("Exception thrown in method3"); } public static void main (String args[]){ try{ method1(); } catch (Exception exception){ exception.printStackTrace(); } } }

输出:

java.lang.Exception: Exception thrown in method1 at UsingChainedExceptions.method1(UsingChainedExceptions.java:8) at UsingChainedExceptions.main(UsingChainedExceptions.java:27) Caused by: java.lang.Exception: Exception thrown in method2 at UsingChainedExceptions.method2(UsingChainedExceptions.java:17) at UsingChainedExceptions.method1(UsingChainedExceptions.java:5) ... 1 more Caused by: java.lang.Exception: Exception thrown in method3 at UsingChainedExceptions.method3(UsingChainedExceptions.java:22) at UsingChainedExceptions.method2(UsingChainedExceptions.java:14) ... 2 more

从输出中我们可以看出最新的异常是method1方法抛出的异常。以相反的顺序阅读输出文本时,将会显示还剩多少链式异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值