Can I take an input using InputStreamReader in static block?

时间:2018-02-03 09:24:44

标签: java

1 个答案:

答案 0 :(得分:1)

Answer - technically, yes you can.

However, your example is reading a number and throwing it away. The local variable in the static block goes away at the end of the block.

In general, it is a bad idea to read user input that way because:

  • Handling exceptions thrown in a static block is not possible. In your example, if the Scanner fails to read an integer an unchecked exception will be thrown. That will crash your application with an ExceptionInInitializerError ...
  • In some circumstances, it can be difficult to tell when (or even if) a static block will be run
  • This is a gratuitously odd way to write this code. Code like this is a problem for people who have to maintain it.

Normal practice is to read input in code called (directly or indirectly) from the main(String[]) method. That way you can control when it is read, and catch any exceptions using a handler on the "main" thread.