2017-05-24 41 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 
}