자바 튜토리얼 - 6 예외 처리

13089 단어 tutorialjavabeginners
예외 처리는 코드에서 오류 또는 예외가 발생할 때 복구 메커니즘입니다. 예외 처리는 예외가 발생하더라도 프로그램이나 코드가 계속 실행되고 있는지 확인하는 유용한 도구입니다.

예외 처리 생성



Java에서 예외 처리를 생성하려면 try catch 블록을 사용하여 수행할 수 있습니다. try 블록에는 예외가 발생할 가능성이 있는 코드가 포함되어 있습니다. catch 블록에는 예외가 발생한 경우 실행될 코드가 포함되어 있습니다. try catch 블록의 기본 문법입니다.

try {
    // code..
} catch(exception_type e) {
    // code..
}

try catch를 사용하여 예외를 처리하는 예입니다.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        }
    }
}



산출

Exception: / by zero



위의 코드를 보면 이 코드에서 예외가 발생한 후 catch 블록 안의 코드를 실행하여 예외 메시지를 출력한다. 0으로 나눌 수 없어 예외가 발생하거나 예외가 발생했기 때문에 예외가 발생했습니다.
finally 블록도 사용할 수 있습니다. 기본적으로 finally 블록 안의 코드는 예외가 발생하든 안 하든 실행된다.
finally 블록을 사용한 예입니다.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        } finally {
            // execute this code
            System.out.println("I'm done!");
        }
    }
}



산출

Exception: / by zero
I'm done!



위의 코드를 기반으로 예외가 발생하더라도 finally 블록 내부의 코드는 여전히 실행됩니다.

이 코드에서 finally 블록은 코드가 성공적으로 실행되었지만 여전히 실행됩니다.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 10;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        } finally {
            // execute this code
            System.out.println("I'm done!");
        }
    }
}



산출

Result: 2
I'm done!



If the exception occurred inside the try block, the rest of the codes inside try block is ignored.



public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0; // exception is thrown here.
            // this code is ignored
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        }
    }
}


사용자 정의 예외 생성



함수에 의해 예외가 throw될 수 있습니다. 특정 함수가 예외를 던지고 있음을 나타내기 위해. 함수 선언 뒤에 throws 키워드를 사용하십시오.

// example
public static int sum(int[] nums) throws Exception { }


함수의 예외는 try catch 블록을 사용하여 처리할 수 있습니다. 함수에서 throws를 사용한 예입니다.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute a function that throws an exception
            regularFunc(1000);
        } catch (Exception e) {
            // get the exception's message
            System.out.println("Message: " + e.getMessage());
        }
    }

    // create a function that throws RuntimeException
    public static void regularFunc(int num) throws RuntimeException {
        if (num > 100)
            throw new RuntimeException("It's too much!");
        else
            System.out.println("Good to go!");
    }
}



산출

Message: It's too much!



위의 코드를 기반으로 예외가 발생하고 catch 블록 안의 코드가 실행됩니다. 예외 메시지는 RuntimeException() 함수의 regularFunc() 메서드 인수 안에 정의되어 있습니다.

출처


  • 예외에 대해 자세히 알아보십시오link .

  • 이 기사가 Java 프로그래밍 언어를 배우는 데 도움이 되기를 바랍니다. 의견이나 의견이 있으면 아래 토론 섹션에 작성할 수 있습니다.

    좋은 웹페이지 즐겨찾기