Why do you have to write throws exception in a class definition?

前端 未结 9 1233
逝去的感伤
逝去的感伤 2020-12-31 09:04

Coming from C#, I just don\'t get this \'throws exception\' that is written after a class/method definition:

public void Test() throws Exception
         


        
9条回答
  •  清歌不尽
    2020-12-31 09:43

    To answer your specific question, you almost never want to say throws Exception per se.

    The throws clause is notifying users of this method that there is an exceptional case that they will have to handle. For example, you might have an IOException that results from some use of the file manipulating methods (e.g., unable to open the file in question). If you haven't handled that locally, you need to declare that your method throws that exception back to the caller.

    Modern IDEs will notify you that, for checked exceptions, you need to either handle them in your use of the method or throw them out of the method up the call tree (via the throws clause).

提交回复
热议问题