본문 바로가기
Java

[Java] try catch finally 문법

by eyoo 2022. 7. 7.
public class TryMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// try catch finally 문법: 예외를 처리하는 방법
		// 예외가 발생했을때 내가 원하는 코드를 실행시키는 방법
		
		int[] arr = {15, 2, 7};
		
		for (int i = 0; i< 4; i++) {
			System.out.println(arr[i]);
		}
		
		try {
			// 여기에 넣어야 한다.
		}

	}

}

# 배열에 3개의 데이터만 들어있는데 반복문을 4개까지 출력하는것으로 설정하여 배열 인덱스 오류가 발생했다.

 

public class TryMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// try catch finally 문법: 예외를 처리하는 방법
		// 예외가 발생했을때 내가 원하는 코드를 실행시키는 방법
		
		int[] arr = {15, 2, 7};

		try {
			
			for (int i = 0; i< 4; i++) {
				System.out.println(arr[i]);
			}
		} catch (Exception e) { // durltj dPdhlrk skdhaus tlfgodgkf zhemdlqfur
			System.out.println("예외발생 " + e.toString());
		}

	}

}

예외 상황에 따라 다르게 처리할수있다.

public class TryMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// try catch finally 문법: 예외를 처리하는 방법
		// 예외가 발생했을때 내가 원하는 코드를 실행시키는 방법
		
		int[] arr = {15, 2, 7};

		try {
			
			for (int i = 0; i< 4; i++) {
				System.out.println(arr[i]);
			}
		} catch (ArrayIndexOutOfBoundsException e) { // 여기서 예외가 나오면 실행할 코드입력
			System.out.println("배열 인덱스 예외 발생시 처리하는 코드");
			System.out.println(e.getMessage());
		} catch (ArithmeticException e) { 
			System.out.println("연산 예외 발생시 처리하는 코드");
			System.out.println(e.getMessage());
		} catch (Exception e) {
			System.out.println("나머지 모든 예외상황은 여기서 처리");
			System.out.println(e.getMessage());
		}

	}

}
		} catch (ArrayIndexOutOfBoundsException e) { // 여기서 예외가 나오면 실행할 코드입력
			System.out.println("배열 인덱스 예외 발생시 처리하는 코드");
			System.out.println(e.getMessage());
		} 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("예외가 발생한든 발생하지 않든, 꼭 실행해야하는 코드는 여기에 작성");
		}

'Java' 카테고리의 다른 글

[Java] 해시맵(Hashmap)  (0) 2022.07.06
[Java] 리스트  (0) 2022.07.06
[Java] 문자열 처리  (0) 2022.07.06
[Java] 인터페이스(Interface)  (0) 2022.07.06
[Java] 추상(Abstract)  (0) 2022.07.06

댓글