下载此文档

java例子——异常处理.txt


文档分类:IT计算机 | 页数:约4页 举报非法文档有奖
1/4
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/4 下载此文档
文档列表 文档介绍
4 异常处理
Java异常处理的特点

例子:下面我们用伪代码描述一个读文件的函数。
readFile
{
open the file;
determine its size;
allocate memory;
read file into memory;
close the file;
}
这个函数看来简单,但它忽略了以下的潜在错误:
文件不能打开;
文件长度不能确定;
没有分配足够的内存;
读失败;
文件关闭失败。
若要解决这些问题,函数中必须添加许多代码来做错误检测、报错和错误处理。
readFile
{
initialize errorCode = 0;
open the file;
if(the file open)
{
determine its size;
if(got the file length)
{
allocate memory;
if(got Enough memory)
{
read file into memory;
if(read failed)
errorCode = 4;//读失败
}
else
errorCode = 3;//内存分配失败
}
else
errorCode = 2;// 文件长度不能确定
}
else
errorCode = 1;// 文件不能打开
close the file;
if(the file did not close && errorCode = 0)
errorCode = 5 //文件关闭失败
return erroCode;
}
增加了错误处理之后,使原先的代码变得很复杂,而Java的异常处理就可解决该问题。
readFile
{
try
{
open the file;
determine its size;
allocate memory;
read file into memory;
close the file;
}
catch(file open failed)
{
dosomething;
}
catch(size determination failed)
{
dosomething;
}
catch(memory allocation failed)
{
dosomething;
}
catch(read failed)
{
dosomething;
}
}
用户不需在主程序中检测和处理错误,异常处理提供了一种当错误发生时分离所有处理细节和原有代码的方法。
_________________________________________________

假设上例的readFile方法是从主程序的第四级调用的,即由method1调用method2、由method2调用method3、再由method3调用readFile。
method1
{
call method2;
}
method2
{
call method3;
}
method3
{
readFile;
}
近一步假设,只有method1对readFile中的

java例子——异常处理 来自淘豆网m.daumloan.com转载请标明出处.

非法内容举报中心
文档信息
  • 页数4
  • 收藏数0 收藏
  • 顶次数0
  • 上传人iluyuw9
  • 文件大小0 KB
  • 时间2014-10-12