[Java] 예외 (1) (try, catch)

SeongEon Kim·2022년 5월 7일
0

JAVA

목록 보기
32/52

예외(Exception)란, 프로그램을 만든 프로그래머가 상정한 정상적인 처리에서 벗어나는 경우에 이를 처리하기 위한 방법이다.

  1. try - catch 문

아래 코드를 통해 계산 코드에 오류가 발생한 사례를 파악해보자.

package org.opentutorials.javatutorials.exception;
class Calculator{
    int left, right;
    public void setOprands(int left, int right){
        this.left = left;
        this.right = right;
    }
    public void divide(){
        System.out.print("계산결과는 ");
        System.out.print(this.left/this.right);
        System.out.print(" 입니다.");
    }
} 
public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator c1 = new Calculator();
        c1.setOprands(10, 0);
        c1.divide();
    }
}

위의 코드를 실행시키면 오류 메세지가 아래 처럼 뜬다.

계산결과는 Exception in thread "main" java.lang.ArithmeticException: / by zero
    at org.opentutorials.javatutorials.exception.Calculator.divide(CalculatorDemo.java:10)
    at org.opentutorials.javatutorials.exception.CalculatorDemo.main(CalculatorDemo.java:18)

위에서 '계산결과는'이 출력 되고, 그 후로는 모두 오류임을 알 수 있다.
위 코드의 문제를 해결해보자.

package org.opentutorials.javatutorials.exception;
class Calculator{
    int left, right;
    public void setOprands(int left, int right){
        this.left = left;
        this.right = right;
    }
    public void divide(){
        try {
            System.out.print("계산결과는 ");
            System.out.print(this.left/this.right);
            System.out.print(" 입니다.");
            //try안에 있는 호출문이 실행되다가 오류가 발생하면 바로 밑의 catch로 넘어간다.
        } catch(Exception e){
            System.out.println("오류가 발생했습니다 : "+e.getMessage());
            //e.getMessage(); -> 오류에 대한 기본적인 내용을 출력해준다. 상세하지 않다.
        }
    }
} 
public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator c1 = new Calculator();
        c1.setOprands(10, 0);
        c1.divide();
         
        Calculator c2 = new Calculator();
        c2.setOprands(10, 5);
        c2.divide();
    }
}

위의 코드를 실행하면, '계산결과는 오류가 발생했습니다 : /by zero'라고 뜬다.
try문에서 오류가 생겨 cath문으로 넘어가서 catch문 내의 호출이 실행된 것이다.
try 안에는 예외 상황이 발생할 것으로 예상되는 로직을 위치시킨다. 예제에서는 사용자가 setOprands의 두 번째 인자로 숫자 0을 입력했을 때 문제가 발생할 수 있음을 예측할 수 있다. 그래서 이 로직을 try 구문으로 감싼 것이다.

try catch를 아래와 같이 정리해보자.

try {
예외 발생이 예상되는 로직
} catch (예외클래스 인스턴스) {
예외가 발생했을 때 실행되는 로직
}

  1. 뒷수습

위에서 배운 코드를 아래와 같이 조금 수정해보자.

package org.opentutorials.javatutorials.exception;
class Calculator{
    int left, right;
    public void setOprands(int left, int right){
        this.left = left;
        this.right = right;
    }
    public void divide(){
        try {
            System.out.print("계산결과는 ");
            System.out.print(this.left/this.right);
            System.out.print(" 입니다.");
        } catch(Exception e){
            System.out.println("\n\ne.getMessage()\n"+e.getMessage());
            System.out.println("\n\ne.toString()\n"+e.toString());
            //e.getMessage()보다 더 자세한 예외 정보를 제공한다.
            System.out.println("\n\ne.printStackTrace()");
            e.printStackTrace();
            //가장 자세한 예외 정보를 제공한다.
        }
    }
} 
public class CalculatorDemo {
    public static void main(String[] args) {
        Calculator c1 = new Calculator();
        c1.setOprands(10, 0);
        c1.divide();
    }
}

실행시키면 출력은 아래와 같이 된다.

계산결과는 
 
e.getMessage()
/ by zero
 
 
e.toString()
java.lang.ArithmeticException: / by zero
 
 
e.printStackTrace()
java.lang.ArithmeticException: / by zero
    at org.opentutorials.javatutorials.exception.Calculator.divide(CalculatorDemo.java:11)
    at org.opentutorials.javatutorials.exception.CalculatorDemo.main(CalculatorDemo.java:25)

try-catch문을 통해 예외를 처리하고 뒷수습을 해주는 기능들이 아래와 같다.

e.getMessage();
오류에 대한 기본적인 내용을 출력해준다. 상세하지 않다.

e.toString()
e.toString()을 호출한 결과는 java.lang.ArithmeticException: / by zero 이다. e.toString()은 e.getMessage()보다 더 자세한 예외 정보를 제공한다. java.lang.ArithmeticException은 발생한 예외가 어떤 예외에 해당하는지에 대한 정보라고 지금을 생각하자. ArithmeticException 수학적인 계산의 과정에서 발생하는 예외상황을 의미한다. (우리는 어떤 숫자를 0으로 나누려고 하고 있다는 것을 상기하자)

e.printStackTrace()
메소드 getMessage, toString과는 다르게 printStackTrace는 리턴값이 없다. 이 메소드를 호출하면 메소드가 내부적으로 예외 결과를 화면에 출력한다. printStackTrace는 가장 자세한 예외 정보를 제공한다.

profile
꿈을 이루는 사람

0개의 댓글