2

我在抛出和捕获异常时遇到了麻烦。

这是 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?

异常类:

占座:

package a2;

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

无效乘客姓名:

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;
4

2 回答 2

2

最有可能的是,您SeatOccupiedException在两个不同的包中有两个类,您的方法从一个包中抛出该类,而您的代码捕获另一个类。

于 2012-04-13T22:15:24.270 回答
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 */
于 2012-04-13T22:48:57.423 回答