try-catch 문
- try 블록에는 예외가 발생할 가능성이 있는 코드를 작성하고 try 블록 안에서 예외가 발생하는 경우 catch 블록이 수행됨
try {
예외가 발생할 수 있는 코드 부분
} catch(처리할 예외 타입 e) {
try 블록 안에서 예외가 발생했을 때 예외를 처리하는 부분
}
- 프로그래머가 예외를 처리해줘야 하는 예 (배열의 오류 처리)
- FileExceptionHandling.java
public class ArrayExceptionHandling {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
try {
for(int i =0; i<=5; i++)
System.out.println(arr[i]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
System.out.println(e.toString());
}
System.out.println("here");
}
}
try-catch-finally 문
- finally 블럭에서 파일을 닫거나 네트워크를 닫는 등의 리소스 해제 구현을 함
- try{} 블럭이 수행되는 경우, finally{} 블럭은 항상 수행 됨
- 여러 개의 예외 블럭이 있는 경우 각각에서 리소스를 해제하지 않고 finally 블록에서 해제하도록 구현함
- 컴파일러에 의해 예외가 처리 되는 예(파일 에러 처리)
- FileExceptionHandling.java
public class FileExceptionHandling {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("a.txt");
System.out.println("read");
} catch(FileNotFoundException e) {
System.out.println(e);
}finally {
if(fis != null) {
try {
fis.close();
}catch(IOException e) {
e.printStackTrace();
}
}
System.out.println("항상 수행 됩니다.");
}
System.out.println("여기도 수행됩니다.");
}
}
try-with-resources 문
- 리소스를 사용하는 경우 close() 하지 않아도 자동으로 해제되도록 함
- 자바 7부터 제공하는 구문
- 리소스를 try() 내부에서 선언해야 됨
- close()를 명시적으로 호출하지 않아도 try{} 블록에서 열린 리소스는 경우나 예외가 발생한 경우 모두 자동으로 해제됨
- 해당 리소스 클래스가 AutoCloseable 인터페이스를 구현해야 함
- FileinputStream의 경우에는 AutoCloseable을 구현하고 있음
- 자바 9부터 리소스는 try() 외부에서 선언하고 변수만을 try(obj)와 같이 사용할 수 있음
- AutoCloseTest.java
public class AutoCloseTest {
public static void main(String[] args) {
AutoCloseableObj obj = new AutoCloseableObj();
try(obj){
throw new Exception();
}catch(Exception e) {
System.out.println("exception");
}
System.out.println("end");
}
}
예외 처리 미루기
- 예외 처리는 예외가 발생하는 문장에서 try-catch 블록으로 처리하는 방법과 이를 사용하는 부분에서 처리하는 방법 두 가지가 잇음
- throws를 이용하면 예외가 발생할 수 있는 부분을 사용하는 문장에서 예외를 처리할 수 있음
- ThrowsException.java
public class ThrowsException {
public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
Class c = Class.forName(className);
return c;
}
public static void main(String[] args) {
ThrowsException test = new ThrowsException();
try {
test.loadClass("a.txt","java.lang.String");
} catch(ClassNotFoundException e) {
System.out.println(e);
} catch(FileNotFoundException e) {
System.out.println(e);
}
System.out.println("end");
}
}
'프로그래밍 언어 > JAVA(자바) 응용' 카테고리의 다른 글
60.오류의 로그를 남기기 (0) | 2022.06.05 |
---|---|
59.사용자 정의 예외클래스 (0) | 2022.06.03 |
57.예외처리 (0) | 2022.06.02 |
56.스트림을 활용한 패키지 여행 비용 계산 (0) | 2022.06.02 |
55.연산 수행에 대한 구현 reduce() 메서드 (0) | 2022.06.01 |
댓글