전산 관련 시험/프로그래밍(C, JAVA, Python)
[JAVA] Exception 정리
응_비
2024. 10. 7. 21:37
2-1. ArithmeticException
- 설명: 정수를 0으로 나누는 등 산술 오류가 발생할 때 발생합니다.
- 예시:
java
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
int c = a / b; // 0으로 나누기
System.out.println(c);
}
}
- 결과: Exception in thread "main" java.lang.ArithmeticException: / by zero
2-2. NullPointerException
- 설명: 참조하고자 하는 객체가 null일 때 발생합니다.
- 예시:
java
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // null 객체에서 length 호출
}
}
- 결과: Exception in thread "main" java.lang.NullPointerException
2-3. ArrayIndexOutOfBoundsException
- 설명: 배열의 범위를 벗어난 인덱스를 참조할 때 발생합니다.
- 예시:
java
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // 배열의 범위(인덱스)를 벗어남
}
}
- 결과: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
2-4. ClassCastException
- 설명: 잘못된 형변환을 시도할 때 발생합니다.
- 예시:
java
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object x = new Integer(100);
String str = (String) x; // Integer 객체를 String으로 캐스팅 시도
}
}
- 결과: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
2-5. NumberFormatException
- 설명: 숫자로 변환할 수 없는 문자열을 변환하려 할 때 발생합니다.
- 예시:
java
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str = "abc";
int num = Integer.parseInt(str); // "abc" 문자열을 정수로 변환 시도
}
}
- 결과: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
3. 예외 처리
Java에서는 try-catch 블록을 사용하여 예외를 처리할 수 있습니다.
3-1. 예외 처리 예제
java
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
System.out.println(arr[10]); // 배열 범위 벗어나기
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
} catch (Exception e) {
System.out.println("General exception occurred.");
} finally {
System.out.println("This will always execute.");
}
}
}
- 결과:
sql
Array index out of bounds!
This will always execute.
이 예제에서는 배열의 범위를 벗어났을 때 발생하는 ArrayIndexOutOfBoundsException을 처리하고, 마지막에 finally 블록을 사용하여 예외 발생 여부와 관계없이 항상 실행되는 구문을 작성했습니다.