1. 컴파일 오류와 실행 오류
컴파일(Compile) 오류
- 프로그램 코드 작성 중 발생하는 문법적 오류
실행(Runtime) 오류
- 실행 중인 프로그램이 의도 하지 않은 동작(bug)을 하거나 프로그램이 중지 되는 오류
2. 오류와 예외 클래스

3. 예외 (Exception) 클래스

1. try-catch 문

2. 배열 인덱스 예외
public class ArrayExceptionHandling {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
try{
for(int i=0; i<=5; i++){
System.out.println(arr[i]);
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
System.out.println("비정상 종료되지 않았습니다.");
}
}
2. try-catch-finally 문
public class FileExceptionHandling {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("a.txt");
} catch (FileNotFoundException e) {
System.out.println(e);
//return; # return이 수행되도 finally는 수행됨
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("항상 수행 됩니다.");
}
System.out.println("여기도 수행됩니다.");
}
}
3. try-catch-resources 문

public class AutoCloseObj implements AutoCloseable{
@Override
public void close() throws Exception { # try 문에 Exception 발생 시킴 (JVM으로 넘기지 않음)
System.out.println("리소스가 close() 되었습니다"); # 실제로는 여기서 리소스를 반환하는 작업 필요
}
}
public class AutoCloseTest {
public static void main(String[] args) {
AutoCloseObj obj = new AutoCloseObj();
try (obj){
//throw new Exception(); # try 블록이 끝나면 close 수행됨
}catch(Exception e) {
System.out.println("예외 부분 입니다"); # exception 블록이 끝나면 close 수행됨
}
}
}
1. 예외 처리 미루기 (넘기기)
2. 예외 처리 throw
public class ThrowsException {
public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(fileName);
Class c = Class.forName(className);
return c;
}
public static void main(String[] args) {
ThrowsException test = new ThrowsException(); # 예외가 발생할 수 있는 코드를 담은 객체를 생성
try {
test.loadClass("a.txt", "java.lang.String");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}catch (Exception e) { # default 예외처리는 맨 마지막
e.printStackTrace();
}
}
}
try {
test.loadClass("a.txt", "java.lang.String");
} catch (FileNotFoundException | ClassNotFoundException e) {
e.printStackTrace();
}