IT/자바
예외처리 Finally
Beautifulkim
2018. 5. 11. 10:26
package mymain; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class MyMain_Finally { public static void main(String[] args) { // TODO Auto-generated method stub FileReader fr = null; try { //화일열기 fr = new FileReader("src/mymain/MyMain_Finally11.java"); //화일을 읽어서 출력 int ch; while(true) { ch = fr.read(); if(ch==-1)break; System.out.printf("%c",ch); if(ch=='\n') throw new IOException("--한줄읽고 끝내기--"); } } catch (FileNotFoundException e) { // TODO: handle exception e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { //닫기(마무리) try { if(fr != null) { fr.close(); System.out.println("--파일닫기--"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package mymain;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MyMain_Finally {
public static void main(String[] args) {
FileReader fr = null;
try
{
//화일열기
fr = new FileReader("src/mymain/MyMain_Finally1.java");
//화일을 읽어서 출력
int ch;
while(true) {
ch = fr.read();
// file의 끝이면 빠져나와라
if(ch==-1) break;
System.out.printf("%c", ch);
// 한줄의 맨 끝 ch=='\n'
if(ch=='\n') throw new IOException("한줄 읽고 끝내기");
}
}
catch (FileNotFoundException e) // fr = new FileReader("src/mymain/MyMain_Finally.java");
{
e.printStackTrace();
} catch (IOException e) { // ch = fr.read();
e.printStackTrace();
}
//석래 아저씨가 해주신 코드 : 굳이 finally를 작성할 필요가 없음
//닫기(마무리)
try
{
//파일을 열었으면 받아라.
if(fr !=null )
{
// close() 는 인스턴스 메소드
fr.close();
System.out.println("--파일 닫기--");
}
}
catch (IOException e) // 파일의 입출력에 관련된 예외
{
e.printStackTrace();
}
}
}