Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

예외 처리와 미루기 본문

Java/다양한 기능

예외 처리와 미루기

Seung__ 2021. 10. 30. 00:05

1. try - catch 문


  • try 블록에는 예외가 발생할 가능성이 있는 코드 작성.
  • try 블록 안에서 예외가 발생하면 catch 블록이 수행됨
  • try-catch로 예외 처리를 하면 예외 발생시 비정상 종료가 되지 않고 계속 실행됨.
try{
	예외가 발생할 수 있는 코드 
} catch(처리할 예외 타입 e){
	try 블록 안에서 예외가 발생했을 때 예외를 처리하는 부분
} 

//정상 상황 일 경우 실행되는 구간
//try-catch로 예외처리를 하지 않으면 예외 발생시 해당 구간 실행되지 않고 비정상 종료
//try-catch로 예외처리 하면 예외 발생해도 코드가 실행됨.
public class ArrayIndexException {

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};

        try{
            for (int i = 0; i <= 5; i++) {
                System.out.println(arr[i]);
            }
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(" 예외 : " + e.getMessage());
            System.out.println(e.toString());
        }

        //catch를 통해 예외를 처리하면 실행됨. -> 죽지 않음
        //만약 예외 처리를 안하면 catch에서 중단됨.
        //물론 정상 상황일 경우에도 실행됨.
        System.out.println("here~~~");
    }
}

 

 

2. try - catch - finally


  • finally 블럭에서 파일을 닫거나 네트워크를 닫는 등의 리소스 해제 구현을 함.
  • try{} 블럭이 수행되는 경우, finally{}블럭은 항상 수행 됨
  • return이 있어소 fianlly는 수행 됨
  • 여러 개의 예외 블럭이 잇는 경우 각각에서 리소스를 해제하지 않고 finally 블록에서 해제하도록 함.
  • 컴파일러에 의해 예외가 처리되는 예.(파일 에러 처리)
try{
	예외가 발생할 수 있는 코드 
} catch(처리할 예외 타입 e){
	try 블록 안에서 예외가 발생했을 때 예외를 처리하는 부분
} finally{
	항상 수행됨
}
  • 직접 사용해 보면 알겠지만.. 코드가 너저분해 진다.. ㅜㅜㅜ
  • 가독성이 많이 안좋아짐.
public class FileExceptionHandling {

    public static void main(String[] args) {

        FileInputStream fis = null;

        try {

            fis = new FileInputStream("a.txt");

        } catch (FileNotFoundException e) {
            System.out.println(e);
           // return ;
        } finally {

            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("finally");
        }

        System.out.println("end");
    }
}

 

 

 

3. try - with -  resources


  • 리소스를 사용하는 경우 close()하지 않아도 자동으로 해제 되도록 함
  • 자바 7부터 제공
  • 리소스를 try{}내부에서 선언해야만 함
    • try(리소스 선언){}
  • close()를 명시적으로 호출하지 않아도, try{}블록에서 열린 리소스는, 정상적인 경우나 예외가 발생한 경우 모두 자동으로 해제됨.
  • 해당 리소스가  AutoCloseable 인터페이스를 구현해야 함.
  • FileInputStream의 경우에응 AutoCloseable을 구현하고 있음.
  • 자바 9부터는 리소스는 try{}외부에서 선언하고 변수만을 try(obj)와 같이 사용할 수 있음.
  • 자바 7기준
public class FileExceptionHandling {

    public static void main(String[] args) {

       // FileInputStream fis = null;

        try(FileInputStream fis = new FileInputStream("a.txt")) {

            System.out.println("read");
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("end");
    }
}
  • 어떻게 자동으로 클로즈? 리소스가 AutoCloseable 구현했기 때문.

3. AutoCloseable 예제

  • AutoCloseable 구현한 객체
public class AutoCloseableObj implements AutoCloseable{
    @Override
    public void close() throws Exception {
        System.out.println("close");
    }
}
  • 자바9 기준으로 외부에서 리소스 선언하고 try(리소스명) 으로 사용이 가능.
public class AutoCloseTest {

    public static void main(String[] args) {

        AutoCloseableObj obj = new AutoCloseableObj();

        try(obj){
            throw new Exception();
        }catch (Exception e){
            System.out.println("exception");
        }

        System.out.println("end");
    }
}

 

 

4. throws


  • 메서드에서 예외를 직접 처리하지 않고 throws를 통해 메서드를 호출한 쪽 에서 처리하도록 함.
public class ThrowException {


    //예외를 메서드 호출하는 곳에서 처리함
    public Class loadClass(String fileName, String className ) throws ClassNotFoundException, FileNotFoundException {
        FileInputStream fis = new FileInputStream(fileName);
        Class c = Class.forName(className);
        return c;
    }

    public static void main(String[] args) {

        ThrowException test = new ThrowException();

        try {
            test.loadClass("a.txt", "abc");
        } catch (ClassNotFoundException | FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (Exception e){ //위에서 catch 못하는 예외를 최상위Exception으로 처리
            System.out.println(e.getMessage());
        }

        /*
        try {
            test.loadClass("a.txt", "abc");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        */
        
        System.out.println("end");
    }
}

 

 

5. GitHub : 211029 try-catch & resource


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

자바 입출력을 위한 I/O Stream  (0) 2021.10.31
사용자 정의 예외 클래스 활용  (0) 2021.10.31
예외 처리  (0) 2021.10.29
Stream활용 예시  (0) 2021.10.29
reduce()  (0) 2021.10.28
Comments