java入门 -- Java I/O(四) 异常处理

/*

* I/O异常处理

* 1.当出现IO异常,需要阻止代码的执行,同时需要抛出异常,将异常信息告知调用者,后面的代码需要继续执行;

* 停止程序的方法有:return和throw,但是return不能告知出现错误的原因,因此用throw来抛出异常

*

*

*/

package com.michael.iodetail;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

class Dmeo3 {

public static void main(String[] args){

}

public static void ioHandle(){

FileInputStream fileInputStream = null;

try {

//1.定位目标文件

File file = new File("d:\\data.txt");

//2.创建文件读通道

byte[] buf = new byte[1024];

int length = 0;

fileInputStream = new FileInputStream(file);

while((length=fileInputStream.read(buf))!=-1){

}

}catch(IOException e){

//将真正的异常包装为运行时异常,使用方便,不用调用者使用的时候就处理.

throw new RuntimeException(e);

}finally{

try {

if(fileInputStream!=null){

fileInputStream.close();

System.out.println("关闭资源成功");

}

} catch (IOException e) {

// TODO Auto-generated catch block

System.out.println("关闭资源失败");

throw new RuntimeException(e);

}

}

}

}

你可能感兴趣的:(java入门 -- Java I/O(四) 异常处理)