如何在Java中抛出一般异常?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)

考虑这个简单的程序。该程序有两个文件:

Vehicle.java:


class Vehicle {
    private int speed = 0;
    private int maxSpeed = 100;

    public int getSpeed()
    {
        return speed;
    }

    public int getMaxSpeed()
    {
        return maxSpeed;
    }

    public void speedUp(int increment)
    {
        if(speed + increment > maxSpeed){
            // throw exception
        }else{
            speed += increment;
        }
    }

    public void speedDown(int decrement)
    {
        if(speed - decrement < 0){
            // throw exception
        }else{
            speed -= decrement;
        }
    }
}

和HelloWorld.java:

public class HelloWorld {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Vehicle v1 = new Vehicle();
        Vehicle v2 = new Vehicle();

            // do something

            // print something useful, TODO         
        System.out.println(v1.getSpeed());
    }

}

正如你在第一课中所看到的,我添加了一个评论(“// throw exception”),我想抛出一个异常。我是否必须为异常定义自己的类或者是否有一些Java中可以使用的常规异常类?

提问于
用户回答回答于

You could create your own Exception class:

public class InvalidSpeedException extends Exception {

  public InvalidSpeedException(String message){
     super(message);
  }

}

在您的代码中:

throw new InvalidSpeedException("TOO HIGH");
用户回答回答于

你可以使用IllegalArgumentException:

public void speedDown(int decrement)
{
    if(speed - decrement < 0){
        throw new IllegalArgumentException("Final speed can not be less than zero");
    }else{
        speed -= decrement;
    }
}

扫码关注云+社区