考虑这个简单的程序。该程序有两个文件:
File 车辆.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;
}
}
}
File 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());
}
}
正如您在第一堂课中看到的,我在我想抛出异常的地方添加了一条注释(“//抛出异常”)。我是否必须为异常定义自己的类,或者 Java 中有一些我可以使用的通用异常类吗?
您可以创建自己的异常类:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
在你的代码中:
throw new InvalidSpeedException("TOO HIGH");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)