int[] arr = new int[3];
System.out.println(arr[10]); // ArrayIndexOutOfBoundsException 발생
3. 예외 기본 문법
try-catch 구조
try {
// 예외가 발생할 수 있는 코드
} catch (예외타입 변수명) {
// 예외가 발생했을 때 실행할 코드
}
4. 예외 예시 1: 0으로 나누기
public class Example1 {
public static void main(String[] args) {
try {
int result = 10 / 0; // 여기서 예외 발생
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
}
}
}
5. 예외 예시 2: 배열 인덱스
public class Example2 {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열 인덱스 초과!");
}
}
}
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException 등
[ 실습 ]
사용자로부터 숫자 두 개를 입력받아 나누기 연산을 수행
0으로 나누면 "0으로 나눌 수 없습니다" 출력
힌트: Scanner, try-catch, ArithmeticException 사용
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("숫자 두 개를 입력 해주세요.");
System.out.print("첫번째 숫자: ");
int a = sc.nextInt();
System.out.print("두번째 숫자: ");
int b = sc.nextInt();
int result = a / b;
System.out.println("a 나누기 b는 " + result);
} catch (ArithmeticException e) {
System.out.println("0으로는 나눌 수 없습니다.");
} finally {
sc.close();
System.out.println("프로그램 실행");
}
}
}
[ 메모 ]
예외는 프로그램 실행 중에 발생하는 비정상적인 상황을 말한다.
예를들어 0으로 나누기, 선언한 배열 크기의 범위를 초과, null을 참조하려고 할 때 예외가 발생한다.
그래서 종류는 ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException 등이 있다.
예외는 기본 구조가 try-catch로 되어 있다.
try { 예외 발생할 수 있는 코드 } catch (예외타입 변수명) { 예외 발생했을 때 실행할 코드 }
예외는 기본 구조외에 try-catch-catch 형식으로 다중 catch를 사용할 수 있다.
try-catch에서 catch () { ... } 이렇게 작성하는데 ( ) 소괄호 안에 예외타입을 작성하면 된다.
catch ( ) 소괄호에 들어가는건 예외타입 변수명인데, 예외타입이 발생하면 중괄호 안의 코드가 실행되는 것이다.
try-catch-finally도 있는데 finally는 예외 발생 여부와 상관없이 항상 실행되는 블록이다.