码迷,mamicode.com
首页 > 编程语言 > 详细

Java程序设计进阶之路三:异常

时间:2016-07-02 22:45:08      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

一、读取文件的步骤:

技术分享

 读取文件操作的每一步都依赖上一步的实现

 

二、代码分析

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程序设计进阶之路三:异常

标签:

原文地址:http://www.cnblogs.com/benbenji/p/5636109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!