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

标签 java exception

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

文件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 中的一些通用异常类?

最佳答案

您可以创建自己的异常类:

public class InvalidSpeedException extends Exception {

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

}

在您的代码中:

throw new InvalidSpeedException("TOO HIGH");

关于java - 如何在 Java 中抛出一般异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6942624/

相关文章:

java - 如何传递 NULL 数据类型?

java - 将长字符串写入 HTML 文件,InputStream、FileWriter 与 BufferedReader

java - 使用 EL 传递 `<portlet:param>` 中的值

c++ - 关于 operator new 重载和异常的问题

java - 列出 retainAll 异常

java - 为什么我的 catch block 永远循环?

java - 输入流根据内容由不同的对象处理

java - 调用 C 子例程时出现 JNI 错误

java - 是否必须处理运行时异常?

c# - 在 IDE 外部运行时为 “Index was outside the bounds of the array”