我們以三種對代碼不一樣的處理方式來看一看異常的優點:
沒有處理錯誤的程序:
read-file {
openTheFile;
determine its size;
allocate that much memory;
closeTheFile;
}
以常規方法處理錯誤
openFiles;
if (theFilesOpen) {
determine the lenth of the file;
if (gotTheFileLength){
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) errorCode=-1;
else errorCode=1;
}else errorCode=-3;
}else errorCode=-5 ;
}else errorCode=-5;