예외(Exception)
예외란 error의 일종이며 프로그램이 수행시 또는 컴파일 시에 불능 상태를 만든다.
이런 불능상태로 들어가기 전에 처리하여 불능상태를 만들지 않기 위해 Exception 예외처리라는 방법을 통해
Exception Error를 처리한다.
예외처리라는것은 Exception 예외가 발생할 것을 대비하여 미리 예측해 이를 소스상에서 제어하고 처리하도록 만드는
것이다. 이렇게 예외처리를 하게 되면 갑작스러운 Exception이 발생해도 시스템 및 프로그램이 불능상태가 되지 않고
정상 실행을 유지할 수 있다.
오류란?
컴파일 오류 : 프로그램 코드 작성 중 발생하는 문법적 오류
실행 오류 : 실행중인 프로그램이 의도하지 않은 동작을 하거나(Bug) 프로그램이 중지되는 오류(Runtime Error)
자바는 예외처리를 통하여 프로그램의 비정상 종료를 막고 log를 남길 수 있다.
오류와 예외클래스
시스템오류(error) : 가상 머신에서 발생하여 프로그래머가 처리할 수 없다.
동적메모리를 다 사용한 경우다 Stack over flow 등
예외(Exception) : 프로그램에서 제어할 수 없는 오류다.
읽으려는 파일이 없는 경우나 네트워크 소켓연결 오류 등이 있다.
자바프로그램에서는 예외에 대한 처리를 수행한다.
예외클래스
모든 예외클래스의 최상위 클래스는 Exception 클래스다.
예외처리
try-catch 문으로 예외처리하기
try {
//예외가 발생할 수 있는 코드
}catch(처리할 예외타입 e) {
//try블록 안에서 예외가 발생했을 때 수행되는 코드
}
예제코드
//try catch
public class ArrayExceptionTest {
int[] arr = new int[5];
try {
for(int i = 0; i <= 5; i++) {
System.out.println(arr[i]);
}
}catch(ArrayIndexOutofBoundsException e) {
System.out.println(e);
System.out.println("예외처리 중");
}
System.out.println("프로그램 종료");
}
/*
반복문을 try안에 넣지 않고 돌리면
OutOfBoundsException 이 발생한다.
배열은 5의 크기를 갖고 있는데
반복문은 0에서 5까지 반복시키니까 마지막
arr[5]가 없기 때문에 발생.
*/
try-catch-finally 문으로 예외처리하기
try {
//예외발생 코드
}catch(처리할 예외타입 e) {
//try블록 안에서 예외가 발생했을 때 수행되는 코드
}finally {
//예외발생 여부와 상관없이 항상 수행되는 코드
//리소스 해제하는 코드를 주로 사용
}
예제코드
/*
프로젝트내에 a.txt를 만들고 코드 실행
try-catch-finally
*/
public class ExceptionTest {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("a.txt");
}catch(FileNotFoundException e) {
System.out.println(e);
return;
}finally {
try {
fis.close();
System.out.println("finally");
}catch(Exception e) {
System.out.println(e);
}
}
System.out.println("end");
}
}
FileInputStream 은 close로 닫아줘야 한다. 첫 try문 안에서 닫아줘도 되지만 오류가 발생한다면
close에 도달하지 못하기 때문에 finally에서 처리하도록 해 Exception이 발생하던 안하던 처리하도록 해준다.
그리고 finally 내부에서 close를 실행했지만 코드에서 fis가 null이기 때문에 finally는 출력하지 않고
catch에서 예외처리를 한다.
그리고 만약 a.tx파일을 만들지 않고 실행하게 된다면 첫 catch에서 return을 하기 때문에 end 역시 출력되지
않는다.
try-with-resources
리소스를 자동으로 해제하도록 제공해주는 구문이다.
해당 리소스가 AutoCloseable을 구현한 경우 close()를 명시적으로 호출하지 않아도 try블록에서 오픈된 리소스는
정상적인 경우나 예외가 발생한 경우 모두 자동으로 close()가 호출된다.
자바 7부터 제공이 되며 FileInputStream의 경우는 AutoCloseable을 구현하고 있다.
예제코드
//try-with-resources 방식
public class ResouceExceptionTest {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("a.txt")) {
}catch(FileNotFoundException e) {
System.out.println(e);
}catch(IOException e) {
System.out.println(e);
}
System.out.println("end");
}
}
이러한 형태로 사용하고 IOException은 AutoCloseable이 수행되지 않았을 경우가 있을 수 있기 때문에
IOException으로 처리하도록 한다.
예제코드2
//AutoClose가 어떻게 처리되는지를 확인하기 위한 예제
//AutoCloseable
public class AutoCloseObj implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("close 호출");
}
}
//Test Class
public class CloseAutoTest {
public static void main(String[] args) {
try(AutoCloseObj obj = new AutoCloseObj()) {
throw new Exception();
}catch(Exception e) {
System.out.println(e);
}
}
}
결과값으로 close 호출 java.lang.Exception 이 출력되는 것을 확인할 수 있다.
Exception이 발생된 이후에도 close가 호출된다.
레퍼런스
● 패스트캠퍼스 올인원 패키지 - 자바 객체지향프로그래밍
'JAVA' 카테고리의 다른 글
제네릭프로그래밍(Generic Programming) (0) | 2021.02.09 |
---|---|
컬렉션 프레임워크(Collection Framework) (0) | 2021.02.08 |
내부클래스(Inner Class) (0) | 2021.02.05 |
Class 클래스 (0) | 2021.02.04 |
Object 클래스 (0) | 2021.02.03 |