==========================
IO异常处理:
1 首先我们的资源释放close放在finally块里是最好的
包装异常
RuntimeException的构造方法:
RuntimeException(Throwable cause)
用指定的原因和详细消息 (cause==null ? null :cause.toString()) 构造一个新的运行时异常(它通常包含类和 cause 的详细消息)
如果我们直接写throw new IOException,那么就需要在方法上声明throws IOException,然后在调用方法的地方还需要去
捕获,很麻烦,所以可以用RuntimeException包装起来,让其编译的时候不出错,因为它有一个构造方法,就是传入原因的,真正的原
因还是IOException,所以我们传入IOException定义的变量即可,Throwable是所有类的父类,
所以IOException定义的变量可以传入,因为多态,这个时候我们就不需要抛出了
class Test
{
public static void main(String[] args)
{
imgCopy();
}
// 下面是图片的复制
public static void imgCopy()
{
FileInputStream fip1 = null;
FileOutputStream fop1 = null;
try
{
File file1 = new File("D:\\w.jpg");
File file2 = new File("C:\\w.jpg");
fip1 = new FileInputStream(file1);
fop1 = new FileOutputStream(file2);
byte[] arr = new byte[1024];
int length = 0;
while ((length = fip1.read(arr)) != -1)
{
fop1.write(arr, 0, length);
}
} catch (IOException e)
{
// 要求异常后后面的代码不执行,但是我们要看到异常的具体信息出来,且方便调用者调用
System.out.println("读取写入文件异常,");
throw new RuntimeException(e);
} finally
{
try
{
// fop1.close();假如这个关闭失败,那么下面的就不执行了,我们要尽可能的关闭所有资源
// fip1.close();
if (fop1 != null)
{
fop1.close();
System.out.println("关闭输出资源成功");
}
} catch (IOException e)
{
System.out.println("关闭输出资源出错");
throw new RuntimeException(e);
} finally
{
try
{
System.out.println("==========是否进入测试=======");
if (fip1 != null)
{
fip1.close();
System.out.println("关闭输入资源成功");
}
} catch (IOException e)
{
System.out.println("关闭输入资源出错");
throw new RuntimeException(e);
}
}
}
System.out.println("这代码执行不执行?执行就正常,不执行就不正常");
}
}