Home Exception
Post
Cancel

Exception

프로젝트에서 예외처리를 구현하며 다시 한 번 예외/에러에 대해 정리하기 위해 작성한 글입니다. 학습 과정에서 작성된 글이기 때문에 잘못된 내용이 있을 수 있으며, 이에 대한 지적이나 피드백은 언제든 환영입니다.

image







1. Exception과 Error


Java에서는 Exception과 Error 두 가지 클래스로 예외 처리를 지원합니다. 둘 다 Throwable 클래스의 하위 클래스로, 프로그램 실행 중 발생하는 오류나 예외를 표현합니다. Exception과 Error는 예외 처리에 사용되지만, 그들의 목적과 사용 측면에서 차이가 있습니다.

image









1-1. Exception

프로그램 동작 중 발생하는 예외적인 상황을 나타내며, 대부분은 개발자가 처리할 수 있습니다. 이는 더 세분화된 Checked ExceptionUnchecked Exception으로 나뉩니다.





Checked Exception은 컴파일 시점에 체크되며, 반드시 개발자가 처리해야 하는 예외입니다. 예를 들어, 파일이 존재하지 않는 경우나 네트워크 연결 오류 등이 이에 해당합니다. 이는 try/catch 블록을 이용한 처리나 throws 키워드를 이용한 예외 위임으로 처리할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
    public static void main(String[] args) {
        try {
            String content = readFile("hello-world.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFile(String filename) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        StringBuilder sb = new StringBuilder();
        String line;
        
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }
        br.close();
        return sb.toString();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Main {

    public static void main(String[] args) {
        try {
            String response = connectToWebsite("https://www.google.com");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String connect(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            return "Connection successful!";
        } else if (responseCode == 404) {

        }
        
        ......
        
    }
}









Unchecked Exception은 주로 프로그래밍 오류 때문에 발생하며, 컴파일러가 예외 처리를 강제하지 않습니다. 이는 RuntimeException 클래스를 상속하는 예외들로 NullPointerException이나 ArrayIndexOutOfBoundsException과 같은 예외들이 있습니다.

1
2
3
4
5
6
7
8
9
10
public class Main {
    public static void main(String[] args) {
        String str = null;
        try {
            int length = str.length();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
}









1-2. Error

시스템 레벨에서 발생하는 심각한 문제를 나타냅니다. 이러한 문제들은 프로그램이 정상적으로 복구되는 것을 방해하며, 개발자가 직접 해결하기 어렵습니다. 그렇기 때문에 에러에 대한 대응보다는 그것들의 예방이 중요합니다. 특히, StackOverflowError와 OutOfMemoryError와 같은 에러가 대표적입니다.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a “normal” condition, is also a subclass of Error because most applications should not try to catch it. A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.









Error와 그 하위 클래스들은 unchecked 예외로 간주됩니다. 따라서 개발자들이 이를 명시적으로 처리할 필요가 없습니다.

That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.









2. 정리


Checked Exception은 RuntimeException과 Error를 제외한 Exception 하위 클래스를 의미하며, Unchecked Exception은 RuntimeException을 상속받는 Exception 하위 클래스를 의미합니다.



This post is licensed under CC BY 4.0 by the author.