優(yōu)勢(shì)2:向調(diào)用堆棧上層傳遞錯(cuò)誤
異常處理的第二個(gè)優(yōu)勢(shì)是向方法的調(diào)用堆棧上層傳遞錯(cuò)誤報(bào)告的能力。假如readFile方法是主程序調(diào)用的一系列嵌套方法中的第四個(gè)方法:方法1調(diào)用方法2,方法2調(diào)用方法3,方法3調(diào)用readFile,代碼結(jié)構(gòu)如下所示:
method1 { call method2; } method2 { call method3; } method3 { call readFile; }
還假如method1是唯一的能夠處理readFile方法中所可能發(fā)生的錯(cuò)誤的方法,那么傳統(tǒng)的錯(cuò)誤處理技術(shù)會(huì)強(qiáng)制method2和method3來(lái)傳遞通過(guò)readFile調(diào)用堆棧所返回的錯(cuò)誤代碼,直到錯(cuò)誤代碼傳遞到method1-因?yàn)橹挥衜ethod1能夠處理這些錯(cuò)誤,其代碼結(jié)構(gòu)如下所示:
method1 { errorCodeType error; error = call method2; if (error)
doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error)
return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error)
return error; else proceed; }
回憶一下,Java運(yùn)行時(shí)環(huán)境搜尋調(diào)用堆棧來(lái)查找任意的處理特殊的異常的方法。一個(gè)方法能夠拋出它內(nèi)部的任何異常,所以允許一個(gè)上層調(diào)用堆棧的方法來(lái)捕獲它。因此只有處理相關(guān)錯(cuò)誤的方法來(lái)處理發(fā)現(xiàn)的錯(cuò)誤,代碼結(jié)構(gòu)如下所示:
method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }
無(wú)論怎樣,就像偽代碼所展示的那樣,躲避異常需要中間方法做一些工作。任意被檢查到的由內(nèi)部方法的拋出的異常必須在這個(gè)方法的throws子句中被指定。
|
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!