본문 바로가기

JAVA

[ JAVA / 자바 ] try catch finally 사용법

 try catch finally

- try 구문에서 에러가 나면 try의 남은 소스를 더이상 진행하지 않고 catch에서 예외 처리를 한다. 그 후, 남은 코드를 실행한다.

- finally 구문은 try catch 이후 마지막에 반드시 실행된다.

- 정상 동작 시, try의 코드를 다 진행하고 남은 코드를 실행한다.

- 개발자가 예외 처리를 해줄 수 있다.

 

ArithmeticException 어떤 수를 0으로 나눌 때 발생함
NullPointerException null 객체를 참조하는 경우
ClassCastException 적절치 못하게 클래스를 형변환하는 경우
NegativeArraySizeException 배열의 크기가 음수값인 경우
OutOfMemoryException 사용 가능한 메모리가 없는 경우
NoClassDefFoundException 원하는 클래스를 찾지 못한 경우
ArrayIndexOutOfBoundsException 배열을 참조하는 인덱스가 잘못된 경우

 

• 사용 예제

import java.util.ArrayList;

public class TryMain {

	// try catch finally 문법 : 예외를 처리하는 방법
	// 예외가 발생했을 때, 내가 원하는 코드를 실행시키는 방법
	
	public static void main(String[] args) {

		int[] arr = {15, 2, 7};
		
		try {
			
			for (int i=0; i<3; i++) {
				System.out.println(arr[i]);
			}		
			
		} catch (ArrayIndexOutOfBoundsException e) {

			System.out.println("배열 인덱스 예외 발생 시 처리코드");
			System.out.println(e.toString());
			
		} catch (ArithmeticException e) {
			
			System.out.println("연산 예외 발생 시 처리코드");
			System.out.println(e.getMessage());
			
		} catch (Exception e) {
			
			System.out.println("나머지 모든 예외 상황은 여기서 처리");
			System.out.println(e.getMessage());
			
		} finally {
			System.out.println("===================================================");
			System.out.println("예외 발생하든 발생하지 않든, 꼭 실행해야 하는 코드는 여기 작성");
		}
		
		
	}

}

 

실행 결과