Java

[Java] 예외 처리(Exception)

에띠 2022. 4. 18. 13:19
728x90

예외처리(Exception)

오류(error)
- 자바 컴파일러에 의해 문법 오류를 발생
- 문법이 맞게 작성되었다 하더라도 프로그램을 실행하면서 예상하지 못한 오류가 발생할 수 있음(예외)

예외(exception)
- 프로그램 실행 중 비성장적으로 종료
- 예측할 수 있는 에러, 예측하지 못하는 예외
- 런타임 시 발생

 


예외가 발생하는 원인
- 사용자가 잘못된 데이터를 입력하는 경우
- 개발자가 로직이나 계산을 잘못 작성한 경우
- 하드웨어나 네트워크가 제대로 동작하지 못하는 경우
- 악의적으로 잘못된 연산을 요구하거나 시스템을 공격

 


예외처리
- 예외란 error의 일종이며, 발생시 시스템 및 프로그램을 불능상태로 만듬
- 예외가 발생할 것을 대비하여 미리 예측해 이를 소스상에서 제어하고 처리하도록 만드는 것

 

 

예외의 종류
1. Exception(일반 예외)
2. RuntimeException(실행 예외)

 

 

✅ Exception을 처리하기 위해 자바에서는 java.lang.Exception을 제공

                        Exception(최상위)

    컴파일 시 발생하는 Exception
    ClassNotFoundException, InterrupedException ..

    프로그램 실행 시 발생하는 Runtime Exception
    RuntimeException ...

Checked Exception(컴파일 시)    Unchecked Exception(런타임 시)
반드시 예외를 처리 명시적인 처리를 강제하지 않음
컴파일 단계 실행 단계
Exception의 상속받은 하위클래스 중 Runtime Exception을 제외한 모든 예외 RuntimeException 하위 예외
roll-back 하지 않음 roll-back 함

 

예외처리 방법

try {
    // 실제 코드가 들어가는 곳으로, 예외 상황이 발생할 가능성이 있는 코드를 작성
    ...
} catch(예외객체타입1 참조변수1) {
    // try 블록에서 Exception이 발생하면 catch 블록으로 오게됨
} catch(예외객체타입2 참조변수2) {
   // try 블록에서 Exception이 발생하면 catch 블록으로 오게됨
} catch(예외객체타입3 참조변수3) {
   // try 블록에서 Exception이 발생하면 catch 블록으로 오게됨
}
	...
} finally {
    // try블록에서 Exception 발생의 유무와 상관없이 무조건 실행되는 코드(옵션, 생략가능)
}

 

코드 진행 순서
1. 예외가 발생하지 않았을 경우
    try문장 -> finally
2. 예외가 발생했을 경우
    try문장 -> 예외에 맞는 catch문장 -> finally

 


Exception1 클래스

public class Exception1 {
    public static void main(String[] args) {
        try {
//            int num = 10;
//            int result = num / 0;
//            System.out.println(result);

//            String str = null;
//            System.out.println(str.length());

//            int[] num = new int[3];
//            num[0] = 100;
//            num[3] = 10;

            String str = "1000 ";
            System.out.println(Integer.parseInt(str));

        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 처리완료!");
            e.printStackTrace(); // Exception 내용을 반환해줌.
        } catch (NullPointerException e) {
            System.out.println("NullPointerException 처리완료!");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException 처리완료!");
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException 처리완료!");
        }
        System.out.println("프로그램을 종료합니다."); // 예외처리를 해야 실행

    }
}

 

Exception2 클래스

 

import java.util.InputMismatchException;
import java.util.Scanner;

public class Exception2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int value = 0;
        try {
            System.out.print("숫자를 입력하세요 : ");
            value = sc.nextInt();
        } catch(InputMismatchException e) {// 블록에서 처리가 되면 다음 블록(Exception e)으로 이동하지 않음.
            value = -1;
            System.out.println("InputMismatchException 발생!"); 
        } catch (Exception e) {
            // Exception 최상위 객체(모든 Exception 처리 가능하지만 세세한 처리는 불가. )
            // 상단에 작성해버리면 모든 예외를 여기서 처리하므로 최하단에 작성해야 함.(에러남.)
            value = -2;
            System.out.println("Exception 발생!");
        } finally {

            System.out.println("현재 value 값 : " + value);
        }
    }
}

 

Exception3 클래스

public class Exception3 {
    public static void main(String[] args) {

        try {
            Class object = Class.forName("com.koreait.test"); // Class.forName() : 패키지네임 읽어와서 객체 생성
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("프로그램을 종료합니다.");

    }
}

강제로 예외를 발생시키는 방법

Exception 참조변수 = new Exception("예외가 발생하면 출력될 문자열");

throw 참조변수; // 예외가 발생!


throw
- 강제로 예외를 발생시키고자 할 때 사용
- 현재 메소드의 예외를 처리한 후 상위 메소드에 예외정보를 전달함

public class Exception4 {
    public static void main(String[] args) {
        try {
            Exception e = new Exception("예외를 발생합니다!");
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("프로그램을 종료합니다");
    }
}


throws
- 현재 메소드에서 자신을 호출한 상위 메소드로 예외를 발생시킴
- 사용하는 메소드를 호출한 상위 메소드에서 예외처리에 대한 책임을 맡김

public class Exception5 {
    public static void main(String[] args) throws Exception{ // 최상위 메소드에서 책임을 전가할 경우 JVM이 알아서 Exception 처리
        method1();
    }

    public static void method1() throws Exception { // 현재 메소드를 호출한 상위 메소드(main)로 책임 전가
        method2();
    }

    public static void method2() throws Exception{ // 현재 메소드를 호출한 상위 메소드(method1())로 책임 전가
        System.out.println("method2() 호출!");
//        Exception e = new Exception("예외가 발생!");
//        throw e;

//        try {
//            throw new Exception("예외가 발생!");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        throw new Exception("예외가 발생!");
    }
}

 

 

728x90