위와같이 main 에 throws Exception 해주지 않거나 try-catch 로 예외처리 하지 않으면 readLine() 메서드에 에러가 나는 이유가 갑자기 궁금해져 집요하게 파보았다.
사실 이런건 왜 발생하는가 보다 발생했을때 어디서 어떻게 처리할까 를 중점으로 고민하는것이 좋지만 어쩔수 없는 성격상 피치 못하게 파헤쳐 보게 되었다..ㅎㅎ
일단 IOException은 checkedException 이기 때문에 반드시 예외처리를 해야한다.
readLine() 을 까보았다.
일단 리턴타입이 boolean 이다.
synchronized(lock) 은 쉽게 동시에 호출되는것을 막아주는 메서드인데, lock을 걸고 한번에 한 사용자만 readLine 메서드에 접근해서 InputStreamReader가 열렸는지를 확인받는다.
그래서 synchronized 가 호출하고있는 ensureOpen() 메서드를 까보았다.
in == null 이면 IOException 을 던지는 구조이다.
in이 null이라는건 Reader(여기서는 키보드와의 connection) 가 프로그램에 인식되지 않는다는 의미이고, 이때 예외처리를 던진다.
자원이 없는데 강제로 read 시키면 프로그램 장애를 유발하는데, 미리 예외처리를 해서 막는것이다.
키보드 입력이 null 이라는게 접근 객체가 없다는 의미라고 생각했는데, 그건 inputstream=0 인것이고 inputstream=null 은 아예 자원이 인식이 되지 않는것을 의미했다.
혼자 개발할 때는 없는 일이지만, 실서비스로 넘어가면 종종 생기는 예외라고한다.
결론 : readLine() 에서 throwsException 하는 이유는 InputStream==null 일때의 장애를 대비해서 미리 예외처리를 해줘야했던것.
'Java > Standard' 카테고리의 다른 글
break 와 continue의 차이 (2) | 2020.06.20 |
---|---|
Scanner.nextInt() / nextLine() 오류 : 두가지 해결방법 (0) | 2020.06.19 |
반복문 : while 과 do~while (0) | 2020.06.18 |
반복문 완전 기초 이해하기 : for문 (0) | 2020.06.18 |
2진수,8진수,16진수의 모든것 (17) | 2020.06.16 |