배운것들을 정리합니다.
三昧境

Java/Java Language

[Java 기초] 예외처리 Exception, Try-Catch, Throw, Finally

ujo_orr 2024. 11. 28. 17:54

예외처리(Try-Catch)

프로그램 내에서 발생 가능한 문제 상황 처리

/*
try {
  명령문
} catch(변수) {
  예외처리
}
*/

public class Main {
  public static void main(String[] args) {
    int[] numbers = {1,2,3};
    int index = 5; // 존재하지 않는 인덱스
  
    try { // try-catch 문
      int result = numbers[index];
      System.out.println("결과 : " + result);
    } catch(Exception e) {
      System.out.println("예외" + e);
    }
  }
}

catch

예외의 종류에 따른 처리

/*
try {
  명령문
} catch(변수1) {
  예외처리1
} catch(변수2) {
  예외처리2
}
*/

public class Main {
  public static void main(String[] args) {
    int[] numbers = {1,2,3};
    int index = 5; // 존재하지 않는 인덱스
  
    try { // try-catch 문
      int result = numbers[index];
      System.out.println("결과 : " + result);
    } catch(ArrayIndexOutOfBoundsException e) { // 잘못된 인덱스를 잡았을시
      System.out.println("예외" + e);
    }
  }
}

예외 발생시키기(Throw)

의도적으로 예외 상황 만들기

/*
throw new 예외();
*/

public class Main {
  public static void main(String[] args) {
    try {
      int age = -5;
      if (age < 0) {
        throw new Exception("나이는 음수일 수 없습니다"); // 예외 발생시키기
      }
    } catch(Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

Finally

예외의 발생여부와 상관없이 항상 실행되는 코드
코드에서 사용된 리소스 해제, 정리작업을 하기위해 주로 사용됨

/*
try {
  명령문
} catch (변수) {
  예외처리
} finally {
  명령문
}
*/

public class Main {
  public static void main(String[] args) {
    try {
      int result = 3/0; // 0으로 나누기 실패
    } catch(Exception e) {
      System.out.println("문제 발생"); 
    } finally {
      System.out,println("실행 종료");
    }
  }
}
// 문제 발생, 실행 종료 둘다 발생

public class Main {
  public static void main(String[] args) {
    try {
      int result = 4/2; // 0으로 나누기 실패
    } catch(Exception e) {
      System.out.println("문제 발생"); 
    } finally {
      System.out,println("실행 종료");
    }
  }
} 
// catch 문을 통과하여 실행 종료만 발생

Try Whit Resources

리소스 관리를 보다 편하게 하는 방법
try 뒤에 파라미터() 가 붙음

/*
try(자원할당) { // 자원이 자동으로 할당해제가 됨
  명령문
} catch(변수) {
  예외처리
}
*/

public class Main {
  public static void main(String[] args) {
    try(FileWriter writer = new FileWriter("file.txt")) {
      writer.write("Hi?");
    } catch (Exception e) {
      System.out.println("문제 발생");
    }
  }
}

//원래는

사용자 정의 예외(Custom Exception)

직접 정의한 예외
특정 상황에서 발생시키고자 할 때

/*
class 클래스명 ㄷxtends Exception {

}
*/

class MyException extends Exception {
  public MyException(String message) {
    super(message);
  }
}

public class Main {
  public static void main(String[] args) {
    try {
      int age = -5;
      if (age < 0) {
        throw new MyException("나이는 음수일 수 없습니다");
      }
    } catch(MyException e) {
      System.out.println("문제 발생 : " + e.getMessage());
    }
  } 
}

예외 처리 미루기(Throws)

메소드를 수행하다 문제가 발생했을때 메소드를 호출한 곳에서 예외처리 하기

/*
반환형 메소드명() throws 예외 {
  명령문
}
*/

public static int divide(int a, int b) throws Exceptions { // throws 미루기
  return a / b;
}

public class Main {
  public static void main(String[] args) {
    try {
      divide(3,0);
    } catch (Exception e) {
      System.out.println("0으로 나눌 수 없음");
    }
  }
}