inblog logo
|
Coding_study
    JAVA

    예외 처리의 3가지 방법

    yuzu sim's avatar
    yuzu sim
    Jan 09, 2024
    예외 처리의 3가지 방법

    [ 클래스를 만드는 사람과 main을 만드는 사람이 다를 때 ]

    클래스를 만든 사람은 직감한다. num 값으로 0을 넣으면 터진다는 것을... 그러면 클래스를 만든 사람이 예외처리를 해서 코드를 전달한다.
    notion image
     

    1. CHECKED EXCEPTION 부모가 무조건 감지해서 알려주는 방법 ★

    package ex08.example2; class Cal3 { void divide(int num) throws Exception { System.out.println(10 / num); } } public class TryEx05 { public static void main(String[] args) { Cal3 c3 = new Cal3(); c3.divide(0); } }
    💡
    호출한 곳에서 try-catch 구현하게 메소드에 throws Exception 제약조건만 걸고 넘김
     

     
    package ex08.example2; class Cal3 { void divide(int num) throws Exception { System.out.println(10 / num); } } public class TryEx05 { public static void main(String[] args) { Cal3 c3 = new Cal3(); try { c3.divide(0); } catch (Exception e) { System.out.println("0 ㄴㄴ"); } } }
    notion image
    💡
    해당 코드는 클래스로 작성이 안되어있지만, 보통은 에러 발생 이름으로 class ZeroDivideException extends Exception 이런 식으로 클래스를 만들고, class Cal3 { void divide(int num) throws ZeroDivideException { 이런식으로 만들어서 넘긴다.
     

    2. 라이브러리 만든 사람이 제어권을 가지는 방법

    package ex08; class Cal4 { void divide(int num) { try { System.out.println(10 / num); } catch (Exception e) { System.out.println("0 쓰지마라~"); } } } public class TryEx05 { public static void main(String[] args) { Cal4 c4 = new Cal4(); c4.divide(0); } }
    notion image
    클래스 메소드에서 try-catch 구현을 다 해놨다. = 제어권이 라이브러리 작성자한테 있다. = [ 0 쓰지마라~ ] 라는 말이 고정되어서 나오게 생겼다.
     

    3. 내가 제어권을 가지고 싶다! 문구 마음에 안들어!! 방법

    class Cal4 { void divide(int num) { try { System.out.println(10 / num); } catch (Exception e) { throw new RuntimeException("0 쓰지마라~"); } } } public class TryEx05 { public static void main(String[] args) { Cal4 c4 = new Cal4(); try { c4.divide(0); } catch (Exception e) { System.out.println("0으로 나눌 수 없어요!"); }
    notion image
    💡
    throw로 던져주면 호출한 곳에서 새로 문구를 바꿀 수 있다! throw로 걸어놨으면 제어권을 뺏을 수 있음
     

     
    💡
    그러나… try-catch로 이렇게 묶어버리면 제어권 못 뺏음 ㅠㅠ
    class Cal4 { void divide(int num) { try { System.out.println(10 / num); } catch (Exception e) { System.out.println("0 쓰지마라!"); //throw new RuntimeException("0 쓰지마라~"); } } } public class TryEx05 { public static void main(String[] args) { Cal4 c4 = new Cal4(); try { c4.divide(0); } catch (Exception e) { System.out.println("0으로 나눌 수 없어요!"); }
    💡
    throw는 뺏어요, try-catch는 못뺏어요.
     

     
    💡
    main메소드에 throw Exception로 제약조건을 걸면 JVM한테 토스하는거니 X
     
    Share article

    Coding_study

    RSS·Powered by Inblog