我是java的新手并试图找出它如何在java中使用异常。根据我所读到的......我可以做类似的事情。
@SuppressWarnings("serial")
public class ElevatorFullException extends Exception {
public ElevatorFullException() { super("Elevator is Full");}
}
然后在程序中使用它
public void boardPassenger( int destinationFloorNumber )
throws ElevatorFullException
{
if ( passengerCount == CAPACITY )
{
throw new ElevatorFullException();
}
passengerLeaving[destinationFloorNumber - 1] += 1;
isDestination[destinationFloorNumber -1] = true;
passengerCount += 1;
}
我的程序运行良好,没有例外,但我添加了这个例外,它突破了下面的错误:
线程中的异常“main”java.lang.Error:未解决的编译问题: 未处理的异常类型ElevatorFullException
答案 0 :(得分:1)
try{
boardPassenger(3);
}
catch(ElevatorFullException ee){
//do any processing you need when exception is thrown
}
public void boardPassenger( int destinationFloorNumber ) {
try{
if ( passengerCount == CAPACITY ) {
throw new ElevatorFullException();
}
passengerLeaving[destinationFloorNumber - 1] += 1;
isDestination[destinationFloorNumber -1] = true;
passengerCount += 1;
}
catch (ElevatorFullException ee){
//do any processing you need when exception is thrown
} }