JAVA

[Java] Exception handling (예외처리)

SangRok Jung 2022. 6. 16. 14:53
반응형

Exception handling (예외처리)


Exception

Program 실행시 사용자 또는 System의 문제로 인해 Application이 대응하지 못하는 abnoraml situation.

Code의 문제가 아닌 Run-Time에 발생하는 abnoraml situation.

Exception은 H/W적 처리방식과 S/W적 처리 방식이 있으나 JVM의 경우 별도로 처리하는 logic이 존재하지 않을 경우 종료 처리함.

이것은 더 이상 JAVA 실행 코드의 무결성을 지킬 수 없다고 판단했기 때문이다.

 

 

 

 

 

 

 

원리

모든 예외를 다 처리 할 수 없다.

JVM은 예외를 감지할 수 있다. (전부 처리 할 수 없다.)

JVM이 감지 못하는 예외는 예외가 아니다.

 

 

 

 

 

 

 

오류발생

  1. Code 자체의 문제.
    1. Debugging 해결.
    2. Testting 해결.
  2. Exception 발생
    1. Exception의 감지
      • JVM이 감지한다. 
    2. 해결이 불가능한 Exception(대부분 H/W적 예외).
      • JVM이 처리하며 종료처리한다.
    3. 해결이 가능한 Exception.
      • App이 처리하며 App에서 처리 하지 않은 예외는 JVM이 종료처리한다.

 

 

 

 

 

 

 

다양한 Exception Class

  • java.lang.ArithmeticException
    • 수학 연산의 Exceoption
  • java.util.InputMismatchException 
    • Scanner를 통한 값의 입력 예외
  • ArrayIndexOutOfBounds
    • 배열의 잘못된 Index 접근.
  • ClassCastException
    • 허용 불가능한 형변환을 강제로 진행.
  • NullPointerExeption
    • Null이 저장된 참조변수의 접근.

 

 

* Exception이 발생하면 Exception발생에 따른 ExceptionClassd에 Instnace를 생성하고 Programmer가 이를 처리할 경우 JVM은 integrity가 지켜졌다고 간주한다.

 

 

 

 

 

 

 

 

try-catch

Exception handling을 위한 JAVA 문법

try에서 발생한 Exception을 catch 영역에서 처리하는 방식이다.

 

public class Excep {
    public static void main(String[] args) {
        Scanner kbScan = new Scanner(System.in);

        //try-catch문 :예외 처리.
        
        int a = 0;
        int b = 0;

        try{
            a = kbScan.nextInt();
            b = kbScan.nextInt();
        }
        catch(java.util.InputMismatchException excp){
            System.out.println("잘못 입력 하셨습니다. 다시 입력하세요.");
            kbScan.close();
            return;
        }
        

        kbScan.close();

        System.out.println(a / b);
    }
}

 

 

 

 

 

 

ExceptionHandling의 범위는 try로 Blcok처리하고 이때 try block의 범위는 아래와 같은 기준으로 처리한다.

 

1. Exception이 발생하는 코드 범위.

2. Exception이 발생했을 경우 영향을 받는 코드 범위.

 

 

 

 

 

 

 

하나의 try Block에서 두개 이상의 예외가 발생할 가능성이 있는 경우 catch문을 두개로 구성한다.

 

 

 

 

 

 

 

 

 

Sample Code

public class sample {
    public static void main(String[] args) {
        
        Scanner Scan = new Scanner(System.in);

        int a = 0; int b = 0; int c = 0;
        int expCount = 0;


    do{
        try{
            a = Scan.nextInt();
            b =  Scan.nextInt();
            c = a / b;
            break;
        }
        catch(java.util.InputMismatchException | ArithmeticException excp){
            expCount++;
            Scan.nextLine();  //Keyboard Scan buffer flush.
            System.out.println("Input ERROR. Re Enter.");
        }
    }
    while(expCount < 3);

    if(expCount == 3){
        System.out.println("Exit with 3 input errors.");
    }


        System.out.println("c = " + c);
    }
}

 

 

 

 

 

 

 

 

 

Exception Handling의 책임 전가


Throwable Class

Exception Handling의 최상위 Class

모든 Exception Handling Class는 Throwable Class를 Inheritance 받는다.

 

* getMessage(), printStackTrace() 등의 기능도 Throwable의 Method다.

 

 

 

 

 

 

 

 

 

Stack Roll-Back

 

 

 

 

 

 

 

 

Roll-Back된 Exception의 처리

전달된 Exception은 ArthmeticException이지만 Throwalbe로 처리가 가능하다.

 

 

 

 

 

 

 

 

 

 

Exception Handling 심화


Exception Class의 분류

 

 

Error

  • 비검사 Exception Class.
  • Application의 진행 불가능.
  • 임의의 Inheritance 불가.
  • VirtualMachineError.
  • IOError

 

RuntimeException

  • 일반적으로 Application에서 Exception를 진행 할 수 있는 Class.

 

Exception

  • 검사 예외 Class.
  • 검사를 할 수 있는것이지 해결 가능한 것은 아님.

 

 

 

java.io.IOException

 

 

 

  • try문을 지워보면 Compile Error가 발생하고 IOException은 반드시 검사를 해야하는 Exception에서 Inheritacne된 Exception handling이기 때문에 try문으로 처리한다. 만약 main()이 아닌 Method 내에서 IOException이 발생 할 가능성이 있는 코드가 존재 할 경우 throws keyword를 통해 exception을 명시적으로 표시해야한다.
반응형