어려울 거 같아서 미뤄뒀던 프로그래밍 공부 이번에 숨 딱 참고 Java 다이브 💦
public class Main01 {
public static void main(String[] args) {
String year1 = "1996";
int age1 = 2022 - Integer.parseInt(year1) + 1;
System.out.println(age1);
String year2 = "뭘까";
int age2 = 2022 - Integer.parseInt(year2) + 1;
System.out.println(age2);
System.out.println("--------프로그램을 종료합니다.-------");
}
/*
출력결과)
27
Exception in thread "main" java.lang.NumberFormatException: For input string: "뭘까"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at exception.Main01.main(Main01.java:13)
*/
}
위의 코드를 실행하면 에러가 발생해요.
런타임 에러는 프로그램 자체의 구조적인 문제로 인한 논리적 오류와 자바 가상머신 자체의 문제로 인한 오류, 그리고 예외가 있어요.
Java에서는 try~catch~finally 구문을 통해서 프로그래머가 예외 상황에 대응할 수 있도록 하고있어요.
try{ // 기본적으로 실행되는 부분 }catch( 예외클래스이름 객체이름 ){ // try블록에서 예외가 발생한 경우 이곳으로 제어가 넘어온다. }finally{ // 예외 상황의 발생 여부에 상관없이 무조건 실행되는 부분 // finally 블록은 생략 가능해요. }
public class Main {
public static void main(String[] args) {
int[] arr = new int[3];
try {
for(int i = 0; i < 5; i++) {
arr[i] = i; // i가 3일 때 에러가 발생
System.out.println(arr[i]);
}
}catch( ArrayIndexOutOfBoundsException e) {
System.out.println("에러가 발생했습니다.");
System.out.println("원인 : " + e.getMessage());
e.printStackTrace();
}finally{
System.out.Println("끝")
}
System.out.println("프로그램 종료");
}
/*
출력결과)
0
1
2
에러가 발생했습니다.
원인 : Index 3 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at exception.Main05.main(Main05.java:11)
끝
프로그램 종료
*/
}
catch블록은 에러가 예상되는 상황에 대해 복수로 명시하는 것이 가능해요.
try{ ... }catch( NumberFormatException e ){ ... }catch( ArrayIndexOutOfException e ){ ... }
Java에서 예외 상황을 의미하는 모든 클래스들의 최상위 클래스
try{ ... }catch( NumberFormatException e ){ ... }catch( ArrayIndexOutOfException e ){ ... }catch( Exception e ){ // 더 다양하게 발견할 수 있는 예외를 한꺼번에 처리할 수 있다. ... }
try{ ... }catch( NumberFormatException | ArrayIndexOutOfException e ){ ... }catch( Exception e ){ // 더 다양하게 발견할 수 있는 예외를 한꺼번에 처리할 수 있다. ... }
다음 다이브에서 또 만나요 🌊
출처
https://media.giphy.com/media/l2Je1bFuOpkNpyqYM/giphy.gif
https://media.giphy.com/media/Jbb3KS22397YQ/giphy.gif