inblog logo
|
{CODE-RYU};
    java

    예외 처리, try-catch 구조

    Jan 04, 2024
    예외 처리, try-catch 구조
    Contents
    try-catch 구조예외의 종류
     
    💡
    잘못된 코드, 부정확한 데이터 등 예외적인 상황에서 오류가 발생할 수 있다. 이런 오류를 예외(exception) 이라고 한다.
     
    public class DivideByZero { public static void main(String[] args) { int num = 10 / 0; System.out.println(num); } }
     
    notion image
     
    10을 0으로 나누는 코드를 만들었을 때, 문법적으로는 오류가 없지만 실행 결과는 오류가 난다.
    정수를 0 으로 나누면 무한대의 값이 발생하기 때문이다. 그래서 0의 값은 예외 처리가 필요하다.
     

    try-catch 구조

     
    💡
    try { // 예외가 발생할 수 있는 코드 } catch(예외클래스 변수){ // 예외를 처리하는 코드 } finally { // try-catch 가 종료되면 무조건 실행됨, 생략 가능 }
    public class DivideByZeroOk { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("숫자를 입력하세요: "); int num = sc.nextInt(); int result; try { result = 10 / num; System.out.println(result); } catch (ArithmeticException e) { System.out.println("0은 넣으면 안됨"); } } }
     
    try-catch 를 이용해 0을 예외처리 했다.
    숫자값을 입력받으면 나누기 값을 출력하되, 0 을 입력하면 catch 이후의 코드가 실행된다.
     
    notion image
     

    예외의 종류

    컨파일 익셉션(Compile exception) : 코드 실행 전 확인할 수 있는 예외 런타임 익셉션(Runtile exception) : 코드 실행 후 확인할 수 있는 예외
     
    class divide1 { void divide(int num) throws RuntimeException { System.out.println(10 / num); } } public class DivideByZeroOk { public static void main(String[] args) { divide1 d1 = new divide1(); d1.divide(10); } }
     
    notion image
     
    divide 클래스에서 메서드를 호출한 메인 클래스로 처리를 넘기는 (throws) 코드를 만들었다.
    RuntimeException 은 코드 실행 후 오류 확인이 가능하기 때문에 0을 나눠도 코드 상 오류가 나지 않고, 실행 시 오류를 확인할 수 있다.
     
    notion image
     
     
    class divide1 { void divide(int num) throws Exception { System.out.println(10 / num); } } public class DivideByZeroOk { public static void main(String[] args) { divide1 d1 = new divide1(); d1.divide(0); } }
    notion image
     
    이번에는 Exception 클래스로 변경했다. Exception 클래스는 컨파일 Exception 이라 실행 전 오류를 확인할 수 있다. 그래서 예외처리를 반드시 해야 한다.
     
    class divide1 { void divide(int num) throws Exception { System.out.println(10 / num); } } public class DivideByZeroOk { public static void main(String[] args) { System.out.print("숫자를 입력하세요: "); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); divide1 d1 = new divide1(); try { d1.divide(num); } catch (Exception e) { System.out.println("0은 넣으면 안됨"); } } }
     
    notion image
     
    Share article

    {CODE-RYU};

    RSS·Powered by Inblog