考虑这个简单的程序。该程序有两个文件:
文件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/