異常管理的優(yōu)勢
你已經(jīng)讀了有關什么是異常以及怎樣使用它們的內容,現(xiàn)在是學習在你的程序中使用異常的好處的時候了。 優(yōu)勢1:把規(guī)則代碼與錯誤處理代碼分離 異常處理規(guī)定把錯誤發(fā)生時所要的細節(jié)工作與程序的主邏輯代碼分離。在傳統(tǒng)程序中,錯誤的發(fā)現(xiàn)、報告以及處理經(jīng)常使得代碼混亂。例如,思考下面的偽代碼,這是一個把整個文件讀入內存的方法。
readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } 第一眼看上去,這個函數(shù)似乎很簡單,但是它卻忽略了所發(fā)生下面這些錯誤的可能。
1、 如果不能打開文件,會發(fā)生什么?
2、 如果不能判定文件的大小,會發(fā)生什么?
3、 如果沒有足夠的內存,會發(fā)生什么?
4、 如果讀取失敗,會發(fā)生什么?
5、 如果文件不能關閉。會發(fā)生什么?
要處理這些信息,readFile函數(shù)必須用更多的代碼來做錯誤發(fā)現(xiàn)、報告和處理工作。這個函數(shù)看上去可能象這樣:
errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } 有如此多的錯誤發(fā)現(xiàn)、報告和返回,使得初的7行代碼被埋沒在混亂的錯誤代碼之中。更嚴重的是,代碼的邏輯流已經(jīng)沒有了,這樣使得它很難說明代碼是否正在做著正確的事情:如果函數(shù)在分配內存過程失敗,文件真得的被關閉了嗎?甚至更難保證在三個月之后,你編寫的這段代碼繼續(xù)做正確的事情。
異常處理使你能夠編寫代碼的主工作流并且在別的地方來處理異常信息。如果readFile函數(shù)使用異常處理來代替?zhèn)鹘y(tǒng)的錯誤管理技術,它應該像如下所示的代碼這樣:
readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } 注意:異常處理不會節(jié)省錯誤的發(fā)現(xiàn)、報告、處理的工作量,但是它們能夠幫助你更有效的組織代碼。
|