자바 튜토리얼 - 6 예외 처리
예외 처리 생성
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 insidetry
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()
메서드 인수 안에 정의되어 있습니다.출처
이 기사가 Java 프로그래밍 언어를 배우는 데 도움이 되기를 바랍니다. 의견이나 의견이 있으면 아래 토론 섹션에 작성할 수 있습니다.
Reference
이 문제에 관하여(자바 튜토리얼 - 6 예외 처리), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/nadirbasalamah/java-tutorial-6-exception-handling-3f68텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)