一个if语句中的多个异常处理

时间:2012-04-13 22:09:52

标签: java exception-handling

我在抛出和捕捉异常方面遇到了麻烦。

这是assignSeat()的代码,在另一个类的try块中调用assignSeat。

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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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 */