2015-07-11 122 views
-1

我在java中实现了一个固定大小的Queue,它使用一个常数大小的ArrayList作为基础容器,其中我的front()方法应该返回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); 
     } 

    } 

通过以上述方式编码,我想前()仅返回如果没有抛出异常值,但预期编译器给我“缺少return语句。”那么,有没有什么办法可以让这个函数只在没有抛出异常的情况下返回。

+0

如果该方法具有非'void'返回类型,则*有*返回值或抛出异常。没有其他选择。你想对这两种选择做什么? –

回答

3

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

您可以实现的功能就像这样:

public T front() throws Exception { 

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

    return arrayList.get(frontIndex); 
} 

最后处理该异常在调用函数/客户端

0

为什么如果你之后抓到它,你会使用这个例外吗?您必须返回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); 
    } 

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

+1

异常意味着被捕获,他应该抛出一个错误 – ceph3us

+0

异常可以被捕获,但通常它们被方法调用者捕获,而不是在方法本身中捕获 – user140547

+0

异常与错误有什么区别?错误不应该被捕获 – ceph3us

1

我想前()只返回如果没有抛出异常值

反问:那你想如果抛出异常回报?

这是问题所在。您已声明front()返回某个内容(T的实例)。这意味着,有两个相关的方式终止呼叫front()

  • 它可以返回一些符合类型T正常终止。

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

您不能返回“无”,因为front()必须返回一个值。

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


那么你能做什么?

  • 使SomeException被抛出,其中SomeExceptionException下降可以改变方法签名。 (投掷Exception是一个非常糟糕的主意......)

  • 您可以将throw new Exception更改为throw new SomeException,其中SomeException来自RuntimeException

  • 假设T是引用类型,您可以返回null。 (这将是,如果T是一个类型参数。)


1 - 事实上,有一对夫妇的其他方式,但他们不是在这方面非常有用。例如,您可以拨打System.exit(int)并终止JVM。 (也有结构化的代码,这样你就不需要(冗余)returnthrowexit调用的方式提示:无限循环不需要返回。)

+0

即使您调用'System.exit(int)',您仍然必须返回一个值或抛出异常;编译器在调用System.exit(int)后不知道程序流停止。 –

+0

修辞我可以返回T型或null的任何东西,即使当一个例外将抛出 – ceph3us

+0

谢谢,你的修辞问题使我清楚的事情,我明白了! – charany1

0

这个“榜样”节目当u能抛出异常和返回值的可能性

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 */ 

} 

编辑:

我想这有两个不同的虚拟机,让我吃惊的一个是扔异常第二是跳过catch块并执行代码,因此取决于虚拟机实现