Search code examples
javaurlexceptioninitmalformed

java invalid method declaration; return type requied in init, run


i'm making a mini java game and i got an error while compiling:

error:invalid method declaration;return type requied
public init() throws Exception {
       ^

First version was public void init, but i can't do like that because i need to use try{..}catch(Malformed...) or while compiling i got another error (needs catch blah blah).

This is code:

public void run() throws Exception{
try{
this.zz();
}catch(MalformedURLException me){
throw me;
}
this.zo();
}

Solution

  • error:invalid method declaration;return type requied
    public init() throws Exception {
          ^
    // You are missing the return type 
    

    You forgot to add the return type to the method declaration. Every Java method should specify a return type . If it doesn't return anything to the caller , make it void. In your case it returns a primitive int , so declare int as return type.

    Need to re factor your code a little :

    // return type is int as you are returning primitive int `0`.
    public int init() throws MalformedURLException {
        //...
        try{
         this.zx();
       }catch(MalformedURLException me){
        // log the Exception here
        // me.printStackTrace();
        // logger.error(... exception message ....);
        throw me;
        // in case you return 0 , in spite of the Exception 
        // you will never know about the exceptional situation
       }
       return 0;
     }
    

    Refer JLS 8.4.