标签:
一、读取文件的步骤:
读取文件操作的每一步都依赖上一步的实现
二、代码分析
1、传统型错误码反馈机制
class errorCodeTypeFile{ int errorCode = 0; if(theFileOpened) { determine its size; if(gotTheFileLength ){ allocate that much memory; if(gotEnoughMemory){ read the file into the memory; if(readFailed){ errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if(theFileDidn‘tClose && errorCode == 0){ errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }
通过反馈的错误码,我们可以了解到哪一步发生错误,但是该种代码可读性差,难以修改,逻辑不清晰。
2、添加异常捕捉机制后的代码
try { open the file; determine its size; allocate that much memory; read the file into the memory; close the file; } catch (fileOpenFailed ){ do something; } catch (sizeDeterminedFaile){ do something; } catch (memeoryAllocationFailed){ do something; } catch (readFailed){ do something; } catch (fileClosedFailed){ do something; }
代码添加异常捕捉机制后,通过catch后的语句可以了解到异常种类,而且该代码具有可读性高,逻辑分明,通常把try后语句称为业务逻辑代码,catch后语句称为异常处理代码。
三、今日总结
标签:
原文地址:http://www.cnblogs.com/benbenji/p/5636109.html