Return 仅当没有抛出异常时

Return only if no Exception is thrown

我在 java 中实现了一个固定大小的队列,它使用一个固定大小的 ArrayList 作为底层容器,我的 front() 方法应该 return Queue 的前元素。

   public T front(){


        try{
            if(isEmpty())
                throw new Exception("Queue is Empty- can't return Front element.");
            return arrayList.get(frontIndex);

        }catch (Exception e){
            System.out.println(e);
        }

    }

通过上述方式编码,我希望 front() 到 return 只有在没有抛出异常的情况下才有一个值,但是正如预期的那样,编译器告诉我“缺少 return 语句。”那么,有没有什么办法可以让函数 return 只有在没有抛出异常的情况下才可以。

如果事后捕获它,为什么还要使用异常?您必须 return T 或抛出异常。但是该方法不会抛出异常,因为您正在捕获它。那样做是不是更简单:

   public T front() throws SomeException{ // if SomeException is checked you need to declare it
        if(isEmpty())
            throw new SomeException("Queue is Empty- can't return Front element.");
        return arrayList.get(frontIndex);
    }

您还应该使用更具体的异常,而不是 Exception。

由于您在代码中捕获异常,编译器显示缺少 return 语句错误。

您可以像这样实现功能:

public T front() throws Exception {

    if(isEmpty()) {
       throw new Exception("Queue is Empty- can't return Front element.");
    }

    return arrayList.get(frontIndex);
}

并最终处理调用 function/client 时的异常

I want front() to return a value only if no Exception is thrown

反问:如果抛出异常,你想要到return什么?

问题来了。您已将 front() 声明为 returning 某物(T 的实例)。这意味着有两种相关的方式1 来终止对 front():

的调用
  • 它可以通过returning 符合类型T的东西正常终止。

  • 它可以通过抛出未经检查的异常异常终止。

你不能 return "nothing",因为 front() 必须 return 一个值。

您不能抛出已检查的异常(如 Exception),因为 front() 未声明为抛出任何异常。


那你能做什么?

  • 您可以更改方法签名以便抛出 SomeException,其中 SomeException 源自 Exception。 (扔Exception真是个糟糕的主意...)

  • 您可以将 throw new Exception 更改为 throw new SomeException,其中 SomeExceptionRuntimeException 的后代。

  • 你可以return null假设T是引用类型。 (如果 T 是类型参数。)


1 - 实际上,还有其他几种方法,但它们在这种情况下没有用。例如,您可以调用 System.exit(int) 并终止 JVM。 (并且有一些方法可以构造代码,这样您就不需要在 exit 调用之后使用(冗余的)returnthrow。提示:无限循环不需要 return.)

这个 "example" 显示了 u 可以抛出异常并且 return 值

的可能性
private boolean throwExReturnValue() throws NullPointerException {

    try {

       throw new NullPointerException("HAHA");
    }

    finally {

        return true;
    }
}

private void ExceptionHanler() {

     boolean  myEx; 

     try { 

       myEx = throwExReturnValue(); 

       /** code here will still execute & myEx will have value = true */

     } catch (Exception ex) {

       /** will execute or not (depending on VM) even we throwed an exception */

     }

    /** code will still execute */

}

编辑:

我用两个不同的 VM 尝试了这个,令我惊讶的是,一个是抛出异常,第二个是跳过 catch 块并执行代码,所以它取决于 VM 实现