readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
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; }
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; } }
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
假设method1是唯一关心在readFile内发生了什么错误的方法。传统的错误通知技术强制method1和method2传播readFile返回的错误代码,直到错误代码最后传到method1——而method1是唯一需要返回码的方法。
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运行时系统通过逆向搜索,查找对某个异常感兴趣的任何方法。一个方法可以躲避任何抛给它的异常,从而让一个方法可以把异常抛到更远的调用栈中捕获。因此,只有关心错误的方法,才必须要去检测错误。
method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }
catch (FileNotFoundException e) { ... }
catch (IOException e) { ... }
catch (IOException e) { // Output goes to System.err. e.printStackTrace(); // Send trace to stdout. e.printStackTrace(System.out); }
你甚至可以构建一个可以处理所有异常的异常处理器:
// A (too) general exception handler catch (Exception e) { ... }
转自:http://leaforbook.com/blog/jexception/translate/advantages.html
原文:http://www.cnblogs.com/hihtml5/p/6505801.html