Multiple Exception Handling in one if statement [closed]
- by JA3N
I am having trouble with throwing and catching exceptions.
Here is the code for assignSeat(), assignSeat is called in a try block in another class.
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();
}
}
and here is the code that calls assignSeat() and is in another class (I won't copy the whole class to make it look clearer)
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.
{
}
}
Whats wrong with the try block? why won't it throw the SeatOccupiedException?
Exception classes:
SeatOccupied:
package a2;
public class SeatOccupiedException extends Exception
{
public SeatOccupiedException(){}
}
InvalidPassengerName:
package a2;
public class InvalidPassengerNameException extends Exception
{
public InvalidPassengerNameException() {}
}
Every class I have is in package a2
imports for class that calls 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.*;
imports for class that has assignSeat
package a2;
import java.util.ArrayList;