2017-05-24 42 views
2
public int front(){ 
if(queue.empty()){ 
    while(!stack.empty()){ 
    queue.push(stack.pop()); 
    } 
} 
try{ 
    return queue.peek(); 
}catch(Exception e){ 
    System.out.println("Empty"); 
} 
// What to do here?!!! 
} 

我正在执行queue使用2 stacks。这里是返回queue的前面元素的函数,但是queueemptyexception必须被提出。但是,必须有外tryreturn声明,我很困惑,不明白怎么做如果函数导致异常,如何避免返回值?

回答

3

在这里做什么?

如果抛出一个异常,是不是一种选择,有一点时front()上称为空队列,你可以这样做:这是一个编程错误,所以动作的正确的做法是抛出IllegalStateException,表明。

try{ 
    return queue.peek(); 
}catch(Exception e){ 
    System.out.println("Empty"); 
    throw new IllegalStateException("Empty"); 
} 
// return statement is no longer required here 

所有其他选项都是但从API设计的差了点:你可以保留一个int值,并返回它当队列为空,或者你可以改变返回类型Integer,并返回null,或您可以将返回类型更改为一对intbooleanboolean指示读取是否成功。但是,抛出未经检查的异常更合适,因为用户在询问其前端元素之前必须检查队列是否为空。

+0

线的东西? –

+0

@lord_ozb用int和boolean属性做一个类,比方说。 'QueueFrontStatus',并返回它而不是'int'。 – dasblinkenlight

+0

非常感谢。我会坚持抛出未经检查的异常:) –

0

你可以返回一个整数类型的对象,检查调用代码,看看如果返回值是零。那样如果它是空的,你可以假设它是空的。

你可以做的另一件事是调用代码处理该异常,并有前()方法抛出异常,像这样:

public int front() throws Exception { 
    if(queue.empty()){ 
     while(!stack.empty()){ 
      queue.push(stack.pop()); 
     } 
    } 
    return queue.peek(); 
} 

这意味着,无论采用哪种方法调用前()将不得不处理例外。

0

您的评论是,但你要么在catch块返回null(确保您的主叫检查返回值null尝试使用结果之前),或者你可以抛出一个异常,你会不会做任何事。

1

我怎样才能返回一个对我会抛出一个异常,就

public int front(){ 
    //..code 
    if(queue.isEmpty()) //or whatever the condition for exception is 
     throw new Exception(); //or whatever exception 
    else 
     return queue.peek(); //return value if exception does not occur 
}