异常管理的优势
你已经读了有关什么是异常以及怎样使用它们的内容,现在是学习在你的程序中使用异常的好处的时候了。 优势1:把规则代码与错误处理代码分离 异常处理规定把错误发生时所要的细节工作与程序的主逻辑代码分离。在传统程序中,错误的发现、报告以及处理经常使得代码混乱。例如,思考下面的伪代码,这是一个把整个文件读入内存的方法。
readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } 第一眼看上去,这个函数似乎很简单,但是它却忽略了所发生下面这些错误的可能。
1、 如果不能打开文件,会发生什么?
2、 如果不能判定文件的大小,会发生什么?
3、 如果没有足够的内存,会发生什么?
4、 如果读取失败,会发生什么?
5、 如果文件不能关闭。会发生什么?
要处理这些信息,readFile函数必须用更多的代码来做错误发现、报告和处理工作。这个函数看上去可能象这样:
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; } 有如此多的错误发现、报告和返回,使得初的7行代码被埋没在混乱的错误代码之中。更严重的是,代码的逻辑流已经没有了,这样使得它很难说明代码是否正在做着正确的事情:如果函数在分配内存过程失败,文件真得的被关闭了吗?甚至更难保证在三个月之后,你编写的这段代码继续做正确的事情。
异常处理使你能够编写代码的主工作流并且在别的地方来处理异常信息。如果readFile函数使用异常处理来代替传统的错误管理技术,它应该像如下所示的代码这样:
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; } } 注意:异常处理不会节省错误的发现、报告、处理的工作量,但是它们能够帮助你更有效的组织代码。
|