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

前端 未结 9 1200
逝去的感伤
逝去的感伤 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:48

    Answer more to the topic rather to description: Class can not use "throws" keyword. Only methods and constructors can.

    With little hack you can use throws on initialization block (but not static). You can set throws on constructor and then it will compile.

    public class Example{ // here you can not use throws
    {
        BufferedReader in = new BufferedReader(new FileReader("asdf"));   
    }   
    public AbstractWithConstantsOnly() throws FileNotFoundException {   }
    
    public static void main(String[] args) throws Exception {
        new Example();
    }
    }
    

提交回复
热议问题