如何在 Java 中抛出一般异常? [英] How can I throw a general exception in Java?
本文介绍了如何在 Java 中抛出一般异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个简单的程序.该程序有两个文件:
Consider this simple program. The program has two files:
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());
}
}
正如您在第一堂课中看到的,我在我想抛出异常的地方添加了一条注释(//抛出异常").我是否必须为异常定义自己的类,或者是否可以使用 Java 中的一些通用异常类?
As you can see in the first class, I have added a comment ("// throw exception") where I would like to throw an exception. Do I have to define my own class for exceptions or is there some general exception class in Java I can use?
推荐答案
您可以创建自己的异常类:
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
在您的代码中:
throw new InvalidSpeedException("TOO HIGH");
这篇关于如何在 Java 中抛出一般异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文