컴파일 에러 : 컴파일 시에 발생하는 에러
런타임 에러 : 컴파일은 되지만 실행 시에 발생하는 에러
-에러(Error) : 메모리 부족이나 스택오버플로우와 같이 복구할 수 없는 심각한 오류
-예외(Exception) : 프로그래머에 의해 개발 단계에서 미리 막을 수 있는 오류
논리적 에러 : 컴파일되고 실행되긴 하지만, 프로그램의 의도와 다르게 동작하는 에러로 개발자의 논리적인 오류로 인해 발생

예외 클래스들은 다음과 같이 두 그룹으로 나눠질 수 있다.
1. Exception클래스와 그 자손들
2. Runtime Exception클래스와 그 자손들
Runtime Exception클래스들은 주로 프로그래머의 실수에 의해서 발생될 수 있는 예외들이다.
예시1. ArithmeticException를 발생시키는 코드예시( 수를 0으로 나누거나 0으로 나눈 나머지를 계산하려고 할 때)
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
// 0으로 나누기를 시도하여 ArithmeticException 발생
int result = 5 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
예시2. ArrayIndexOutOfBoundsException 를 발생시키는 코드예시( 배열에 잘못된 인덱스로 접근하려고 할 때 발생하는 예외)
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
try {
// 배열 선언
int[] numbers = {1, 2, 3, 4, 5};
// 유효하지 않은 인덱스에 접근하여 ArrayIndexOutOfBoundsException 발생
int element = numbers[10];
System.out.println("Element at index 10: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
예시3. FileNotFoundException 를 발생시키는 코드예시( 파일이 존재하지 않을 경우 FileNotFoundException이 발생하며, 이는 IOException의 하위 클래스이므로 IOException으로 처리
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
// 파일 경로 지정 (예시로 존재하지 않는 파일을 지정)
String filePath = "nonexistentfile.txt";
try {
// 파일을 읽어오기 위한 BufferedReader 생성
BufferedReader br = new BufferedReader(new FileReader(filePath));
// 파일 내용을 읽어오기
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
// BufferedReader 닫기
br.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}'JavaStudy' 카테고리의 다른 글
| [Java] 래퍼클래스(wrapper) (0) | 2023.12.05 |
|---|---|
| [Java] ArrayList (0) | 2023.12.04 |
| [Java] collections framework (1) | 2023.12.04 |
| [Java] 인터페이스(interface) (0) | 2023.12.02 |
| [Java] Overriding (0) | 2023.11.30 |