지금까지는 남들이 발생시키는 예외에 대해서 처리하는 방법에 대해 알아보았다면, 우리가 우리의 코드에서 예외를 발생시킬 수도 있다.
throw new Exception("문제가 발생했습니다.");
throw new RuntimeException("문제가 발생했습니다.");
public class MyException {
public static void main(String[] args) {
throw new RuntimeException("무언가 문제가 있습니다.");
}
}
이렇게 문제 상황이 발생했을 때, throw 구문을 통해서 예외를 발생시킬 수 있다. 이 경우에는 RuntimeException 객체를 이용하였지만, Exception 객체도 우리가 직접 생성할 수 있다.
try catch 문으로 예외를 처리할 수도 있지만, 우리가 만든 메소드가 우리의 설계 의도대로 돌아가지 않을 경우 메소드 자체에서 예외를 발생시킬 수도 있다.
예외라는 것은 폭탄 돌리기와 비슷하다. 어떤 기능에서 예외가 발생하면, 그것을 직접 처리할 수도 있지만 그 기능을 사용하는 쪽으로 예외를 던질 수도 있다. 이것을 '던진다'는 뜻에서 throw라고 한다. 이렇게 throw를 하다가 어느 지점에서 그 예외를 처리하려고 할 때 우리가 사용하는 것이 try catch 이다. 아무도 try catch 를 하지 않는다면 결국 프로그램은 종료되면서 예외 메세지가 표시된다.
폭탄 돌리기처럼, 우리가 직접 예외를 처리한다기보다는 앞으로 우리의 메소드를 사용할 누군가가 예외를 처리해 주기를 바라는 것과 같다.
import java.io.FileWriter;
import java.io.IOException;
public class ThrowException {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter("./data.txt");
f.write("Hello");
f.close();
}
}
위의 코드에서, FileWriter의 예외를 처리해줘야 한다. try catch 구문으로 감싸줄(surround) 수도 있지만, 또 다른 방법은 이 기능을 이 코드를 사용하는 쪽으로 던질 수 있는 것이다. 쓰는 쪽에서 처리하라는 것이다.
이때 "throws + 위임하고 싶은 예외의 이름"의 방식으로 적는 것이다. 위 코드의 경우 throws IOException이라고 기입했다. 그렇게 되면 에러가 없어진다. 이 코드를 사용하는 쪽에서 try catch의 요구를 받게 된다.
[참고자료]
https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
How to Throw 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
https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
Specifying the Exceptions Thrown by a Method (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/creating.html
Creating Exception Classes (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' 카테고리의 다른 글
try with resource (0) | 2022.11.26 |
---|---|
finally (0) | 2022.11.26 |
Checked Exception vs Unchecked Exception (0) | 2022.11.26 |
catch문의 e (1) | 2022.11.26 |
예외의 우선순위 (0) | 2022.11.26 |