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; }每次客户端调用这个方法,都需要判断返回的状态码,从而来决定下一步来做什么...比如:
int status = readFile(); switch(status){ case -1: do something... case -2: do someting... }
下面是使用异常之后的代码:
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() call method2() call method()3 call readFile()
如果没用异常处理机制,那么每个方法都会被强制进行错误诊断,那可是相当麻烦的,如下代码:
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; }
下面我们使用异常来处理:
method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }
另外,异常可以帮助我们将一些错误进行分类处理。比如在java.io中,需要各种各种的IO错误,比如打开文件失败,访问文件失败,关闭输出流失败等,我们都可以将这些异常归结为IOException,从更加高的层次去看待问题。
抛出了无数的Exception,但是Exception到底是啥?解开Exception的神秘面纱...
原文:http://blog.csdn.net/u010469003/article/details/42916253