import java.util.ArrayList;

public class TryMain {

	// try catch finally 문법 : 예외를 처리하는 방법
	// 예외가 발생했을때, 내가 원하는 코드를 실행시키는 방법
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {15, 2, 7};
		
		try {
			for(int i = 0; i < 3; i++) {
				System.out.println(arr[i]);
			}
			
		ArrayList<String> myList = null;
			
		myList.add("안녕?");
			
		int k = 4 / 0;
			
		System.out.println(k);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 인덱스 예외발생시 처리코드");
			System.out.println(e.toString());
		} catch (ArithmeticException e) {
			System.out.println("연산 예외 발생시 처리하는 코드");
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println("나머지 모든 예외상황은 여기서 처리");
			System.out.println(e.toString());
		} finally {
			System.out.println("예외 발생하든 발생하지 않든, 꼭 실행해야 하는 코드는 여기 작성");
		}

	}

}

try 에 있는 코드를 실행하고 에러가 나면 catch에 있는 예외상황쪽 코드를 실행하고

예외가 발생하든 발생하지 않든 끝날때는 finally를 실행한다.

 

'자바' 카테고리의 다른 글

unable to access jarfile.jar 에러  (0) 2022.09.28
자바 HashMap  (0) 2022.07.06
자바 ArrayList 사용법  (0) 2022.07.06
자바 인터페이스 사용방법  (0) 2022.07.06
자바 추상클래스 용도와 사용방법  (0) 2022.07.06

+ Recent posts