답변:자바에서 예외를 처리하는 구문 try ... catch


[ Follow Ups ] [ Post Followup ] [ 자바 묻고 답하기 ]

Posted by 윤경구 on April 12, 1997 at 08:36:44:

In Reply to: [Q] java.io.IoException must be caught ....? posted by 양정윤 on April 12, 1997 at 03:09:41:

System.in은 InputStream 클래스 인스턴스입니다.
API 문서를 살펴보면 InputStream.read() 도구는 다음과 같이 선언되어 있습니다.


public abstract int read() throws IOException

자바에서 이렇게 런타임에서 예외를 발생시키는 도구는 반드시 try {} catch(){} 블록으로 감싸 예외 처리를 할 수 있어야 합니다.
read가 예외를 일으키는 경우는 갑자기 스트림이 닫겨버린다든가 하는 이유에서일텐데요...
어쨌든 다음과 같이 위 구문을 고치면 컴파일이 됩니다.
위의 소스는 JDK 1.0 (베타?) 버전 정도에서 컴파일되던 것이 아닌가 합니다.
이전 버전에서는 예외를 처리하지 않더라도 warning, 즉 경고로만 처리했었는데
보안 상의 문제 등으로 모두 컴파일 에러로 처리하는 것으로 변경되었습니다. (JDK 1.0 베타3부터이던가요?)


class IfElseName {
public static void main (String args[]) {
char firstInitial=0;
System.out.println("Enter your first initial:");

try {
firstInitial = (char) System.in.read();
}catch(java.io.IOException e) {
e.printStackTrace();
}

if (firstInitial == -1)
System.out.println("Now what kind of name is that!?");
else if (firstInitial == 'j')
System.out.println("Your name must be Jules!");
else if (firstInitial == 'v')
System.out.println("Your name must be Vincent!");
else if (firstInitial == 'z')
System.out.println("Your name must be Zed!");
else
System.out.println("I can't figure out your name!");
}
}





Follow Ups:



Post a Followup

Name:
E-Mail:

Subject:

Comments:

Optional Link URL:
Link Title:
Optional Image URL:


[ Follow Ups ] [ Post Followup ] [ 자바 묻고 답하기 ]