이전글:

2020/12/11 - [JAVA] - 예외처리-1

 

예외처리-1

컴파일 오류: 프로그램 코드 작성중 발생하는 문법적인 오류 실행 오류: 실행 중인 프로그램이 의도하지 않는 동작을 하거나(버그) 프로그램이 중지 되는 오류(runtime error) *자바는 예외처리를 통

kwaksh2319.tistory.com

 

 

FileInputStream 파일을 불러올수 잇는 클래스입니다.

public class Main {

  
	public static void main(String [] args)  {
	
       FileInputStream fis=null;
		
		try {
			fis=new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
		           System.out.println(e);
		}finally {
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
}
 }
			
		}
		System.out.println("first end");

a.txt 파일을 fis로 인스턴스화 합니다.

new FileInputStream("a.txt");

만약 a.txt 파일이 존재하지 않는경우에는 아래와 같이 예외 처리가 됩니다.

이전에 사용했던 try- catch-finally 문들은과 다른 try-with-resource 문을 사용해보겠습니다.

왜   try-with-resource 문을 사용하는가?

stackoverflow.com/questions/17739362/whats-the-purpose-of-try-with-resources-statements

 

What's the purpose of try-with-resources statements?

Java 7 has a new feature called try-with-resources. What is it? Why and where we should use it and where we can take advantage of this feature? The try statement has no catch block which confuses me.

stackoverflow.com

 

여기서 stack overflow의 글을 빌리자면 

try- catch-finally 문:

InputStream stream = new MyInputStream(...);
try {
    // ... use stream
} catch(IOException e) {
   // handle exception
} finally {
    try {
        if(stream != null) {
            stream.close();
        }
    } catch(IOException e) {
        // handle yet another possible exception
    }
}

try-with-resource 문:

try (InputStream stream = new MyInputStream(...)){
    // ... use stream
} catch(IOException e) {
   // handle exception
}

같은 기능을 하는 코드인데 훨씬 보기 좋습니다.

또한 만약 해당 리소스에 java.lang.AutoCloseable를 구현한 경우 close를 명시적으로 호출하지않고 try{} 블록에서 

오픈된 리소스는 정상적인 경우나 예외가 발생한 경우나 모두 close() 함수가 호출됩니다.

예시 : 

AutoClosseObj:

package Test01;

public class AutoCloseObj implements AutoCloseable {

	@Override
	public void close() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("close() 호출");
	}

}

Main:

package Test01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {

  
	public static void main(String [] args)  {
try(FileInputStream res=new FileInputStream("b.txt")){
			
		}catch (FileNotFoundException e) {
			// TODO: handle exception
			System.out.println(e);
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println(e);
		}
		System.out.println("second end");		
		
		
		try(AutoCloseObj obj=new AutoCloseObj()){
			throw new Exception();
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
		//사용자 정의 예외
		//예외처리 미루기
		
		
		
	}
}

 

 

 

 

 

 

 

 

 

'프로그래밍언어 > JAVA' 카테고리의 다른 글

<JAVA>입출력 스트림  (0) 2020.12.12
<JAVA>예외처리-3  (0) 2020.12.11
<JAVA>예외처리-1  (0) 2020.12.11
<JAVA>Stream -2  (0) 2020.12.11
<JAVA>Stream-1  (0) 2020.12.09

+ Recent posts