본문 바로가기

Language/Java

예외 처리 (Exception Handling)

예외가 발생함에도 불구하고 그대로 프로그램을 완성시켰다면 사용자 입장에서는 잘못된 값만 넣어버리면 뻗어버리는, 언제 뻗을지 모르는 불안한 프로그램이라고 생각할 것이다.

 

예외는 발생할지라도 그 뒤의 작업을 실행하기 위해서는 예외 처리(Exception Handling)를 해야 한다.

 

try catch 문을 이용해서 예외를 처리하면 어떤 값을 넣는 경우에도 끝까지 실행되는 튼튼한 프로그램이 된다.

 

가령, 이전에 알아봤던 2를 0으로 나누는 것의 경우,

 

public class ExceptionApp {

	public static void main(String[] args) {
		System.out.println(1);
		try {
			System.out.println(2/0);
		} catch (ArithmeticException e) {
			System.out.println("잘못된 계산이네요.");
		}
		System.out.println(3); 
	}

}

 

이렇게 try catch 문으로 에러가 나는 부분을 감싸주면, Exception이 발생했을 때 그 부분에 대응하는 코드가 실행되고, 나머지 코드가 실행된다.

 

 

위와 같이 Exception에 대응하는 코드인 catch 부분의 코드가 실행되고, 뒤의 3도 함께 출력되는 것이다.

 

이번에는 다른 종류의 Exception에 대해 알아보겠다.

 

public class ExceptionApp {
	public static void main(String[] args) {
    		System.out.println(1);
        	int[] scores = {10, 20, 30};
        	try {
        		System.out.println(scores[3]);
		} catch (ArrayIndexOutOfBoundsException e) {
        		System.out.println("없는 값을 찾고 계시네요.");
		}
        	try {
        		System.out.println(2 / 0);
		} catch (ArithmeticException e) {
        		System.out.println("잘못된 계산이네요.");
		}
        	System.out.println(3);
	}
    
}

 

위 코드의 경우, 배열 scores는 인덱스가 0, 1, 2 세 개 밖에 없는데, scores[3]를 출력하려고 하니 ArrayIndexOutOfBoundsException이 발생했고, 그것을 try catch 문으로 감싸서 처리했다. 위 코드의 경우,

 

 

로 콘솔에 값이 찍힌다.

 

그런데 위에 있는 코드와 밑에 있는 코드를 합칠 수도 있다.

 

public class ExceptionApp2 {
	public static void main(String[] args) {
    		System.out.println(1);
        	int[] scores = {10, 20, 30};
        	try {
        		System.out.println(2);
        		System.out.println(scores[3]);
            		System.out.println(3);
        		System.out.println(2 / 0);
            		System.out.println(4);
		} catch (ArrayIndexOutOfBoundsException e) {
        		System.out.println("없는 값을 찾고 계시네요.");
		} catch (ArithmeticException e) {
        		System.out.println("잘못된 계산이네요.");
		}
        	System.out.println(5);
	}
    
}

 

이렇게 try 구문 안에 scores[3]과 2 / 0을 같이 넣는 것이다. 이 경우에는. 

 

 

이렇게 콘솔에 뜬다. 1이 실행이 됐고, 2가 실행이 됐고, scores[3]의 Exception이 실행된 다음, 마지막에 5가 출력(실행)되었다. try를 하나로 합칠 경우 첫 번째 Exception 이후의 예외들은 출력(실행)되지 않는다는 것을 알 수 있다.

 

 

 

 

 

[참고자료]

https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

 

The Catch or Specify Requirement (The Java™ Tutorials > Essential Java Classes > Exceptions)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

 

Catching and Handling Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

'Language > Java' 카테고리의 다른 글

catch문의 e  (1) 2022.11.26
예외의 우선순위  (0) 2022.11.26
예외 (Exception)  (0) 2022.11.26
다형성 (Polymorphism)  (0) 2022.11.20
인터페이스 (Interface)  (0) 2022.11.20