-
0. JAVA 기초 (10)카테고리 없음 2020. 3. 8. 21:50
package innerClass; import java.io.FileInputStream; import java.io.FileNotFoundException; public class TestException { public static void main(String args[]) { FileInputStream fis = null; try { fis = new FileInputStream("a.txt"); } catch (FileNotFoundException e) { System.out.println(e); } finally { try { fis.close(); // file을 닫아주어야 한다. } catch (Exception e) { // file을 닫는 과정에서도 오류가 날 수 있으므로 try, catch e.printStackTrace(); } } } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class TestException { public static void main(String args[]) { try (FileInputStream fis = new FileInputStream("a.txt")) { // try-catch-resource } catch (IOException e) { } catch (Exception e) { } } }
- close()는 AutoClosable interface에서 수정 가능하다.
public class AutoCloseObj implements AutoCloseable { @Override public void close() throws Exception { System.out.println("close()가 호출되었다."); } }
package innerClass; public class TestAutoClass { public static void main(String[] args) { try( AutoCloseObj obj = new AutoCloseObj()) { throw new Exception(); // 임의로 Exception을 발생시킴 } catch(Exception e){ } } }
- throws() : 예외처리 미루기
- main으로 try,catch를 미루는 예제
package innerClass; import java.io.FileInputStream; import java.io.FileNotFoundException; public class TestThrowsException { public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException { FileInputStream fis = new FileInputStream(fileName); // FileNotFoundException이 발생할 수 있다. Class c = Class.forName(className); // ClassNotFoundException이 발생할 수 있다. return c; } public static void main(String[] args) { TestThrowsException test = new TestThrowsException(); try { test.loadClass("b.txt", "java.lang.string"); } catch (FileNotFoundException e) { System.out.println(e); } catch (ClassNotFoundException e) { System.out.println(e); } } }
- 사용자 정의 예외
package innerClass; public class IDFormatException extends Exception { public IDFormatException(String message) { super(message); } }
package innerClass; public class TestIDFormat { private String userID; public String getUserID() { return userID; } public void setUserID(String userID) throws IDFormatException { if(userID == null) { throw new IDFormatException("아이디는 null 일 수 없다."); } else if(userID.length() < 8 || userID.length() > 20) { throw new IDFormatException("아이디 길이가 잘못됌."); } this.userID = userID; } public static void main(String[] args) { TestIDFormat idTest = new TestIDFormat(); String myID = "aa"; try { idTest.setUserID(myID); } catch (IDFormatException e) { System.out.println(e); } } }