Difference between Throws in method signature and Throw Statements in Java

前端 未结 4 696
不知归路
不知归路 2021-01-30 02:00

I am trying to make it clear of the difference between Throws in method signature and Throw Statements in Java. Throws in method signature is a

4条回答
  •  借酒劲吻你
    2021-01-30 02:08

    Vidya provided great answer to your questions.

    The most important words are "The final point is that you only need to declare an exception in throws when the exception is a checked exception"

    Just to show you an example code what does this mean. Imagine that we would like to use FileOutputStream in order to pass some data. The function would look like this:

    public void saveSomeData() throws IOException {
      FileInputStream in = null;
      FileOutputStream out = null;
    
      try {
        in = new FileInputStream("input.txt");
        out = new FileOutputStream("output.txt");
        int c;
    
        while ((c = out.read() != -1) {
          in.write(c);
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        // Close in
        if (in != null) {
          in.close(); // <-- If something bad happens here it will cause runtime error!
        }
        // Close out
        ...
      }
    }
    

    Now imagine, if you wouldn't provide throws IOException and something bad happens inside finally{} statement - it would cause an error.

提交回复
热议问题