본문 바로가기

JAVA

[JAVA] try / catch / finally

try 문에서 exception 발생 시, 이에 맞는 catch 문으로 들어감.

finally 는 try / catch 문 실행 이후 무조건 실행되는 코드 (주로, connection close 에 사용됨)

강제로 Exception 만든 후, throw 를 통해 발생 가능

public class Practice2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList<Integer> arr = new ArrayList<>();
		
		//System.out.println(arr.get(1));
		try {
        	//강제로 exception 생성
			//Exception e = new Exception();
			//throw e;
			System.out.println(arr.get(1));
			System.out.println("well tried");
		} catch (IndexOutOfBoundsException e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("IndexOutOfBoundsException : " + e);
			//throw e;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("Other Exception : " + e);
			//throw e;
		}
		finally {
			System.out.println("end");
		}
		
		System.out.println("out of try block");
	}
}

-----------
IndexOutOfBoundsException : java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
end
out of try block
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
	at java.util.ArrayList.rangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at Practice2.main(Practice2.java:15)

 

try / catch 문을 사용하지 않았을 경우,

exception 이 발생한 이후 코드 실행 불가.

public class Practice2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList<Integer> arr = new ArrayList<>();
		
		System.out.println(arr.get(1));
		System.out.println("well tried");
		
		System.out.println("out of try block");
	}
}
-------------
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
	at java.util.ArrayList.rangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at Practice2.main(Practice2.java:11)
반응형

'JAVA' 카테고리의 다른 글

[JAVA] 싱글톤 (singleton) 패턴  (0) 2022.02.19
[Springboot] lombok 설치 및 STS 연동  (0) 2022.02.09
[JAVA] 다형성(polymorphism)  (0) 2022.01.17