본문 바로가기
Backend/JAVA_Basic

22. JAVA, 예외 처리 (Exception, try~catch, finally, throws)

by 개발개발빈이 2022. 6. 6.

○  Exception

    - Exception : 자바 클래스 실행(run)시 발생하는 에러

    - exception 예시

 

        ① ArrayIndexOutOfBoundsException

int[] num = new int[3];
num[5]=2;  //ArrayIndexOutOfBoundsException

 

        ② NumberFormatException

int no=Integer.parseInt("KOREA");  //NumberFormatException

 

        ③ NullPointerException

Integer inte=null;
System.out.println(5/inte);  //NullPointerException

 

        ④ ArithmeticException

System.out.println(1/0);  //ArithmeticException

 

○  예외처리

    - Exception이 발생하면 프로그램은 정상적으로 종료되지 않음 

System.out.println(1);
System.out.println(3/0);   //ArithmeticException발생, 프로그램이 정상적으로 종료되지 않음
System.out.println(5);     //출력되지 않음
System.out.println("END"); //출력되지 않음

 

    - Exception이 발생하더라도 정상적으로 프로그램은 종료시키기 위해 예외처리가 필요

    - 형식) try { 예외 발생이 예상되는 코드 } catch(Exception e) { 예외발생시 처리할 코드

try {
    System.out.println(1);
    System.out.println(3/0);  //ArithmeticException발생
    System.out.println(5);    //출력되지 않음
}catch(ArithmeticException e) {
    System.out.println(e);   //출력됨(java.lang.ArithmeticException: / by zero)
}

System.out.println("END");   //출력됨

 

    - 다중 catch문

catch(NumberFormatException e) {
    System.out.println(e);
}catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(e);
}catch(NullPointerException e) {
    System.out.println(e);
}
System.out.println("END");

 

○  Exception 클래스

    - 모든 예외 발생의 조상 클래스

    - 서브클래스로 exception 목록이 모두 들어가 있음

    - Exception클래스로 catch문 처리 가능

출처 : https://docs.oracle.com/javase/8/docs/api/

try {
    int a=2/0;
    int b=Integer.parseInt("KOREA");
    int[] num=new int[3];
    num[5]=7;
}catch(Exception e) {
    System.out.println(e);
}
System.out.println("END");

 

○  finally문

    - 예외가 발생하든 발생하지 않든 무조건 실행

    - 형식) try { 예외 발생이 예상되는 코드 } catch(Exception e) { 예외발생시 처리할 코드 } finally { 항상 실행할 코드 }

try {
    System.out.println("OPEN");
    System.out.println(1/0);
}catch (Exception e) {
    System.out.println(e);
}finally {
    System.out.println("CLOSE");
}
System.out.println("END");

 

○  throws를 이용한 예외처리

    - 메소드(함수) 호출 시 예외처리를 한꺼번에 모아서 처리

    - 메소드에만 적용할 수 있는 명령어, 메소드 작성시 함수명 옆에 붙여줌

class Test {

    public void view() throws Exception { 

        int a=3/0;
        System.out.println(a);

    }//view() end

    public void disp() throws NullPointerException, NumberFormatException { 

        int a= Integer.parseInt("KOREA");
        System.out.println(a);

    }//disp() end

}//class end


public class Test02_throws {

	public static void main(String[] args) {
		
		try {
			Test test = new Test();
			test.disp();
			test.view();
		}catch (Exception e) {
			System.out.println(e);
		}
		
	}//main() end

}//class end

 

    - 참고) throws처럼 메소드에만 적용할 수 있는 명령어 synchronized

                → OS가 개입해서 문제가 발생하지 않도록 조정하는 기법

public synchronized void login() {}

댓글