【问题标题】:java invalid method declaration; return type requied in init, runjava 无效的方法声明; init 所需的返回类型,运行
【发布时间】:2013-07-26 11:39:40
【问题描述】:

我正在制作一个迷你java游戏,编译时出错:

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

第一个版本是 public void init,但我不能那样做,因为我需要使用 try{..}catch(Malformed...) 或者在编译时出现另一个错误(需要 catch blah blah)。

这是代码:

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

【问题讨论】:

  • public void init() 抛出异常
  • public int init() 抛出异常。添加返回类型。

标签: java url exception init malformed


【解决方案1】:

您忘记添加返回类型。由于您返回 0,我假设您要返回一个 int。所以把你的标题改成:

public int init() throws MalformedURLException

没有理由拥有throws Exception。尽可能具体。

一般来说,方法的语法是:

访问修饰符 (public, protected, private) 返回类型 (primitive, object, void) 方法名

这是Defining Methods 上的 Oracle 教程。

另外,不确定这是否适用,但如果您只打算返回 0 或 1,例如,请考虑将您的方法标头更改为:

public boolean init() throws MalformedURLException

【讨论】:

    【解决方案2】:
    error:invalid method declaration;return type requied
    public init() throws Exception {
          ^
    // You are missing the return type 
    

    您忘记在方法声明中添加返回类型。每个 Java 方法都应该指定一个返回类型。如果它没有向调用者返回任何内容,请将其设为void。在您的情况下,它返回一个原始 int ,因此将 int 声明为返回类型。

    需要稍微重构您的代码:

    // 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;
     }
    

    请参考JLS 8.4

    【讨论】:

    • 是的,但我不能使用 void,因为需要 MalformedURLException 否则 url 将不起作用。
    • @user2622574 我没听明白。请多解释一下。
    • 如果我使用void,我不能使用return。我需要使用 try{...}catch MalformedURLException,因为 this.zx 有 URL(file...)。 try..catch 格式错误的需求返回
    • 不,它不需要 return ,你可以简单地抛出 Exception 。
    • 错误:xray 中的 run() 无法在 Runnable 中实现 run() public void run() throws Exception{ ..........^
    【解决方案3】:

    返回类型是强制性的。你必须提供一个。我猜是逃不掉的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      相关资源
      最近更新 更多