자바 프로그램상 예기치 않은 상황에서 문제가 발생할 수 있다.
이러한 상황에서 예외처리를 통해 문제를 해결한다.
Exception : 자바가 처리할 수 있는 상황
- Checked Exception : 컴파일 시점에서 처리할 수 있는 예외 상황
Ex) 파일 입출력 , 커넥션 연결 등
- Unchecked Exception : 런타임 상황에서 확인 할 수 있는 예외 상황
Ex) Nullpoint, divided 0 , arraybound 등
Error : 자바가 처리할 수 없는 심각한 오류 (Server error , Out of Memory)
Try ~ Catch 블록
public class Main {
public static void main(String args[])
{
try
{
//something wrong
}
catch (Exception e)
{
//exception 발생 후 상황
}
}
}
오류가 발생하는 메서드에서 직접 try catch 블록으로 감싸 예외 처리
Throws
public class Ex {
public void ex1()
{
try
{
ex2();
}
catch (Exception e)
{
}
}
private void ex2() throws Exception{
//something error
}
}
예외가 발생하는 메서드가 아닌 해당 메서드를 사용한 Caller에게 예외를 전달 후 처리
Throw
예외상황을 인위적으로 발생 시키는 명령어
private void ex2() throws Exception{
throw new Exception("Exception");
}
time out 등 실제로 예외처리가 필요한 상황에서 발생시킴
예외처리 finally 와 System.exit(0) , return
System.exit(0) : 소스코드상 프로그램을 즉시 강제 종료
return : 해당 메서드를 끝냄 , 메인 쓰레드가 바로 종료되지 않음
1. catch에서 System.exit 발생시 finally 블록
public class Main {
public static void main(String args[])
{
try
{
throw new Exception("Exception");
}
catch (Exception e)
{
System.exit(0);
}
finally
{
System.out.println("System End");
}
}
}
결과 : catch 에서 System.out을 호출하여 바로 종료 시키므로 finally 블록으로 넘어가지 않음
2. return 발생시 finally 블록
public class Main {
public static void main(String args[])
{
try
{
throw new Exception("Exception");
}
catch (Exception e)
{
return;
}
finally
{
System.out.println("System End");
}
}
}
결과 : return이 수행되더라도 finally 블록을 수행 후 메서드 종료
'Programing Language > JAVA' 카테고리의 다른 글
JAVA Thread 구현하기 (0) | 2021.02.25 |
---|---|
Enumeration과 Iterator (0) | 2021.02.25 |
인터페이스와 디폴트, 스태틱 메서드 (0) | 2021.02.22 |
Abstract Class와 Interface의 차이 (0) | 2021.02.22 |
New String 과 Literal String (0) | 2021.02.22 |