20220821
한 번에 끝내는 Java/Spring 웹 개발 마스터
1) ArrayIndexException
package ch08;
public class ArrayIndexException {
	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.print(e.getMessage());
			System.out.println(e.toString());
		}
		
		System.out.println("Hello");
	}
}
- 배열의 크기보다 더 큰 값을 요구할때 발생하는 오류: ArrayIndexOutOfBoundsException
 
- try - catch문을 통해서 예외처리를 해주면, "Index 5 out of bounds for length" 라는 문구로 예외가 처리되고, 이후에 Hello라는 값이 정상적으로 출력되는 것을 볼 수 있다.
 
2) try - catch - finally
package ch08;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileExceptinonHandling {
	public static void main(String[] args) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("a.txt");
			System.out.println("Read");
		} catch (FileNotFoundException e) {
			System.out.println(e);
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}
			System.out.println("Finally");
		}
		System.out.println("End");
	}
}
- finally문을 마지막에 추가했는데, finally문은 오류가 생성시 반드시 출력되므로, finally라는 문구는 그대로 출력이 된다.
 
3) thorw new
package ch08;
public class AutoCloseTest {
	public static void main(String[] args) {
		
		AutoCloseableObj obj = new AutoCloseableObj();
		
		try(obj) {
			throw new Exception();
			
		} catch(Exception e) {
			System.out.println("exception");
		}
		
		System.out.println("End");
	}
}
- throw부분을 통해서 강제로 Exception을 발생시키고 try catch문으로 받아서 exception이라고 출력되게 하였다.
 
4) EX
package ch08;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ThrowsException {
	public Class loadClass(String fileName, String className) throws ClassNotFoundException, FileNotFoundException {
		
		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 (ClassNotFoundException e) {
			System.out.println(e);
		} catch (FileNotFoundException e) {
			System.out.println(e);
		} catch ( Exception e ) {
			
		}
		
		System.out.println("End");
	}
}