java 异常处理技巧
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
//构造函数异常处理特性
public class ExceptionDemo1
{
public static void main(String... args)throws Exception
{
//注意此处采用嵌套try的形式来处理
/**
如果在构造对象时抛出了异常则直接进人外层的try块
*/
String path="";
try
{
InputFile inf=new InputFile(path);
try
{
String s=null;
while ((s = inf.readLine()) != null)
{
System.out.println(s);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally");
inf.dispose();
}
}
catch (Exception e)
{
System.out.println("构造对象失败");
}
}
}
//此类是对FileReader的包装类
class InputFile
{
private BufferedReader br;
//指定文件路径打开文件
public InputFile(String fname)throws Exception
{
try
{
br = new BufferedReader(new FileReader(fname));
}
catch (FileNotFoundException e)
{
System.out.println("文件没找到异常");
//因为文件还没打开 此处不应该关闭流 br.close();
throw e;//此处异常要抛出 否则被隐藏不能被捕获
}
catch (Exception e1)
{
System.out.println("其它异常");
//文件已打开后出现的异常 此处可以关闭流
br.close();
}
finally
{
//此处不能做流关闭operations
}
}
public String readLine()
{
String line=null;
try
{
line = br.readLine();
}
catch (IOException e)
{
System.out.println("读取行失败");
}
return line;
}
//将流的关闭操作单独提供
public void dispose()
{
try
{
br.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}