Java程序设计进阶之路三:异常
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java程序设计进阶之路三:异常相关的知识,希望对你有一定的参考价值。
一、读取文件的步骤:
读取文件操作的每一步都依赖上一步的实现
二、代码分析
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后语句称为异常处理代码。
三、今日总结
以上是关于Java程序设计进阶之路三:异常的主要内容,如果未能解决你的问题,请参考以下文章
JAVA如何进阶架构师,Java进阶之路——从初级程序员到架构师,从小工到专家