예외 처리
백기선님의 Java 스터디를 진행하며 찾아본 내용입니다.
목표
자바의 예외 처리에 대해 학습하세요.
학습할 것
- 자바에서 예외 처리 방법 (try, catch, throw, throws, finally)
- 자바가 제공하는 예외 계층 구조
- Exception과 Error의 차이는?
- RuntimeException과 RE가 아닌 것의 차이는?
- 커스텀한 예외 만드는 방법
자바에서 예외 처리 방법 (try, catch, throw, throws, finally)
Exception이란?
프로그램 실행 중에 발생하는 이벤트로 프로그램 명령의 정상적인 흐름을 방해하는 것
예외(Exception)가 발생하면 메소드는 예외 객체를 형성하여 런타임 시스템에 넘기고 런타임 시스템은 에러를 처리할 수 있는 코드를 찾기위해 'call stack'을 서칭한다.
만약 콜스택을 전부 서칭하고 난 뒤에도 적절한 예외 처리 메소드를 찾지 못한다면 런타임 시스템(프로그램)은 종료된다.
try/catch/finally block
1
2
3
4
5
6
7
8
9
10
11
12
|
try {
// 예외가 발생 할 수 있는 코드
}
catch(ExceptionType1 name) {
// ExceptionType1 예외가 발생할 경우에 실행되는 코드
}
catch(ExceptionType2 name) {
// ExceptionType2 예외가 발생할 경우에 실행되는 코드
}
finally {
// try 블록에서 빠져나갈때 항상 실행되는 코드
}
|
cs |
Try block
예외가 발생되어 질 수 있는 코드가 위치되어진다.
Catch block
try block 바로 뒤에서 발생되어진 예외를 처리한다.
다음 코드와 같이 다중의 에러를 처리 할 수도 있는데, 이 때 Exception의 파라미터 타입은 암시적으로 final로 선언된다.
1
2
3
4
5
|
catch(IOException|SQLException ex) {
logger.log(x);
throw ex;
}
|
cs |
Finally block
try 블록을 빠져나갈 때 반드시 실행되는 블록이다.
예상치 못한 예외가 발생해도 실행되는 것이 보장되어진다.
* try와 catch 코드가 실행되던 도중에 JVM이 꺼지거나 실행되던 스레드가 kill된다면 finally 블록이 실행되지 않을 수도 있다.
Throw / Throws
Throw
예외를 임의로 발생시킬 수 있는 명령어.
Throwable 객체를 상속받는 Throwable sub-class라면 throw 키워드의 argument로 쓸 수 있다.
Example)
1
2
3
4
5
6
7
8
9
10
11
12
|
public Object pop() {
Object obj;
if (size == 0) {
throw new EmptyStackException();
}
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}
|
cs |
위의 메소드는 스택의 맨 위에서 값을 빼내는 메소드이다. 만약 스택이 비어있다면 EmptyStackExcpetion() 객체를 throw한다.
Chained Exception
한 Exception이 다른 예외를 발생 시킬 때가 있는데 Chained Exception이 이걸 구현 하도록 도와준다.
다음과 같은 메소드들이 chained exception을 하는데에 사용된다
// method
Throwable getCause(); // 예외의 실제 원인을 반환한다.
Throwable initCause(Throwable); // 현재 예외의 원인을 설정한다.
// constructor
Throwable(String, Throwable);
Throwable(Throwable);
Example1)
1
2
3
4
5
|
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
|
cs |
위와 같은 코드가 있다고 할 때
throw new SampleException("Other IOException", e)는 생성자인 Throwable(String, Throwable)을 호출한다. 따라서 새로운 SampleException 객체를 만들고, argument에 실제 원인을 붙여서 상위 예외 객체로 예외를 throw하게 된다.
Example2)
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
26
27
28
29
|
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
// Creating an exception
NumberFormatException ex =
new NumberFormatException("Exception");
// Setting a cause of the exception
ex.initCause(new NullPointerException(
"This is actual cause of the exception"));
// Throwing an exception with cause.
throw ex;
}
catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);
// Getting the actual cause of the exception
System.out.println(ex.getCause());
}
}
}
|
cs |
위와같이 initCause를 이용해 원인을 직접 설정해 줄 수도 있다.
throws
메소드가 뒤에 나열된 예외 중의 하나를 throw를 할 수 있다고 알려주기 위해 사용되는 키워드
Syntax:
type method_name(parameters) throws exception_list
자바가 제공하는 예외 계층 구조
Exception과 Error, Runtime Exception의 차이는?
Exception은 3가지로 나뉜다
- Checked Exception
- Error
- Runtime Exception
Checked Exception은 예측할 수 있고 복구 할 수 있는 예외 사항이다. 예를 들어, 유저가 파일의 이름을 입력하도록 요청 받았는데 존재하지 않는 파일의 이름을 입력한다던지 하는 경우가 있을 수 있다.
Error는 애플리케이션 외부에서 일어나는 예외적인 사항을 말하는 것으로 예측 할 수 없고 복구 할 수 없다. 예를 들어 하드웨어나 OS등의 결함 등이 있을 수 있다.
Runtime Exception은 애플리케이션 내부에서 일어나는 예외적인 사항으로 예측 할 수 없고 복구 할 수 없다.
예를 들어 프로그램의 로직을 잘못 짜서 버그가 발생한다던지 API의 잘못된 사용으로 버그가 발생하는 등의 예외가 발생하는 것을 의미한다. catch로 처리 할 수는 있지만 로직등을 고쳐 버그를 제거하는 것이 더 바람직하다.
Custom한 예외 만드는 법
Exception 클래스를 상속받거나 알맞은 예외 클래스를 상속받아 만든다.
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
26
27
28
29
30
|
// A Class that represents use-defined expception
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class Main
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("My Error");
}
catch (MyException ex)
{
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}
|
cs |
Output:
Caught
My Error
Reference
docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
What Is an Exception? (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html
The Catch or Specify Requirement (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
Catching and Handling Exceptions (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/try.html
The try Block (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
The catch Blocks (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
The finally Block (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
How to Throw Exceptions (The Java™ Tutorials > Essential 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
docs.oracle.com/javase/tutorial/essential/exceptions/chained.html
Chained Exceptions (The Java™ Tutorials > Essential 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
www.geeksforgeeks.org/throw-throws-java/
throw and throws in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
www.geeksforgeeks.org/g-fact-32-user-defined-custom-exception-in-java/
User-defined Custom Exception in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
www.javatpoint.com/exception-handling-in-java
Exception Handling in Java | Java Exceptions - javatpoint
Exception Handling in Java or Java Exceptions with checked, unchecked and errors with example and usage of try, catch, throw, throws and finally keywords.
www.javatpoint.com