알고리즘을 풀면서 제일 많이 사용했던 BufferedReader를 사용할때 왜 IOException을 사용해야하는지 궁금해져서 찾아봤다.
BufferedReader는 입력 값을 바이트스트림에서 문자스트림으로 변환해주는 InputStreamReader와 입력 장치를 통해 값을 받아주는 System.in을 사용한다.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
}
여기서 throws IOException으로 예외처리를 하지 않으면 에러가 발생한다.
String readLine(boolean ignoreLF, boolean[] term) throws IOException {
StringBuilder s = null;
int startChar;
synchronized (lock) {
ensureOpen();
readLine 메서드를 뜯어보면 ensureOpen()을 호출하고 있다.
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
/** Checks to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
if (in == null)
throw new IOException("Stream closed");
}
(in == null)일 경우, IOException을 발생시킨다.
in은 BufferedReader의 Reader 클래스에 대한 파라미터이고 InputStreamReader를 파라미터에 넣어서 생성했기 때문에 InputStreamReader를 가리킨다.
여기서 in이 null이라는 것은 Reader가 인식되지 않는다는 뜻인데 자원이 없을때 참조하게 될 경우 에러가 발생하기 때문에 예외처리를 하는 것이다.
키보드의 입력이 없을 때는 inputstream = 0이고
자원이 인식되지 않는 상태는 inputstream = null이다.