[예외처리 1 : 정수만 입력가능하도록!(다른 문자를 입력했을 경우)]
public class ExceptionTest2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("input inteager : ");
int num = 0;
try {
num = scan.nextInt();
} catch (java.util.InputMismatchException e) {
// e.printStackTrace(); // 이 명령문으로 '발생할 에러'의 종류를 알아내어 catch 의 조건으로 걸어주도록 한다.
System.out.println("잘못된 에러입니다.");
}
System.out.println("num is : " + num);
}
}
[ 예외처리 2 : 파일을 열고 읽어올때의 예외 처리(checked exception) ]
public class ExceptionTest3 {
private FileReader reader;
public ExceptionTest3() {
try {
reader = new FileReader("d:/scott.sql");
while(true){
int data = reader.read(); //파일에서 한글자를 읽어온다.
if(data == -1) // 파일의 끝이면 파일 읽어오는 작업 종료.
break; // -1 은 텍스트 파일의 끝;
System.out.print((char)data); // 읽어온 문자 하나씩 출력함.
}
} catch (FileNotFoundException e) {
System.out.println("파일이 존재하지 않거나 이름이 잘못됐습니다.");
} catch (IOException e) {
e.printStackTrace();
} finally{//무조건 실행되는 블록으로 뒷 정리 작업에 주로 사용
try {
reader.close();
} catch (IOException e) {
System.out.println("파일을 열지 못했으므로 닫을 수 없습니다.");
}
}
}
public static void main(String[] args) {
new ExceptionTest3();
}
}
'개발메모장' 카테고리의 다른 글
JAVA 파일 입출력 (0) | 2014.12.18 |
---|---|
JUnit (0) | 2014.12.18 |
Swing Test (0) | 2014.12.18 |
Interface (0) | 2014.12.18 |
lombok 2 (0) | 2014.12.18 |