2012-04-13 49 views
2

我遇到了拋出和捕獲異常的問題。多個異常處理在一個if語句中

以下是assignSeat()的代碼,assignSeat在另一個類的try塊中調用。

void assignSeat(String passengerName, int x, int y) throws SeatOccupiedException, InvalidPassengerNameException 
{ 
    Seat tSeat = airplane.getSeat(x,y); 
    if (tSeat!=null) 
    { 
     if (passengerName.isEmpty() || !passengerName.matches("[a-zA-Z]+")) 
     { 
      throw new InvalidPassengerNameException(); 
     } 
//excluded else if 
    else if (foundPassenger(passengerName)) 
     { 
        airplane.seatList.get(airplane.seatNumber(passengerName)).unOccupy(); 
        tSeat.occupy(); 
        for (int i = 0; i<passengers.size();i++) 
         if (passengers.get(i).getName().equals(passengerName)) 
          passengers.get(i).changeSeat(tSeat.getSeatName()); 
     } 
     else if (!tSeat.occupied) 
     { 
      tSeat.occupy(); 
      addPassenger(passengerName, tSeat.getSeatName()); 
     } 
     else if (tSeat.occupied) 
     { 
      throw new SeatOccupiedException(); 
     } 
    } 

這裏是調用assignSeat(),並在另一個類(我不會複製整個類,使它看起來更清晰)

if (afComp.currentAF != null) 
      { 
       try 
       { 
        afComp.currentAF.assignSeat(nameField.getText(), x, y); //<-Problem here, "Unhandled exception type SeatOccupiedException" 
       } 
       catch (SeatOccupiedException exception) //<-Problem here, "Unreachable catch block, This exception is never thrown from the try statement body" 
       { 

       } 
       catch(InvalidPassengerNameException exception) //<-No problems. 
       { 

       } 
      } 

哪些錯誤與try塊代碼?爲什麼它不會拋出SeatOccupiedException?

異常類:

SeatOccupied:

package a2; 

public class SeatOccupiedException extends Exception 
{ 
    public SeatOccupiedException(){} 
} 

InvalidPassengerName:

package a2; 

public class InvalidPassengerNameException extends Exception 
{ 
    public InvalidPassengerNameException() {} 
} 

每次上課我都在包A2

進口類調用assignSeat

package a2; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseListener; 
import java.awt.event.MouseMotionListener; 
import java.awt.event.MouseEvent; 
import java.awt.BorderLayout; 
import javax.swing.*; 
import javax.swing.event.*; 

進口類,它具有assignSeat

package a2; 
import java.util.ArrayList; 

回答

2

最可能的是,你有兩種不同的封裝2個SeatOccupiedException類,你的方法從一個包投類,而你的代碼捕獲的其他類。

0

變化的邏輯,簡化您的語句:

if (tSeat.occupied) { 
     throw new SeatOccupiedException(); 
    } 

    if (/* bad passenger name */) { 
     throw new InvalidPassengerNameException(); 
    } 

    if (/* passenger does not exist */) { 
     throw new PassengerNotFoundException(); 
    } 

    /* assign Seat here */ 
+0

察看其佔用的需求是foundPassenger後,因爲如果乘客被發現,座椅被佔據世界上沒有問題 – JA3N 2012-04-13 22:55:22

+0

更改簡單的情況下的邏輯。如果工作正常,則可以增加報表的複雜性... – rosco 2012-04-13 23:00:18