考虑这个简单的程序.该程序有两个文件:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
和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());
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在第一个类中看到的,我添加了一个注释("// throw exception"),我想抛出一个异常.我是否必须为异常定义自己的类,或者我可以使用Java中的一些常规异常类吗?
For*_*ega 101
您可以创建自己的Exception类:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的代码中:
throw new InvalidSpeedException("TOO HIGH");
Run Code Online (Sandbox Code Playgroud)
Mau*_*res 41
您可以使用IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
Run Code Online (Sandbox Code Playgroud)
RMT*_*RMT 13
好吧,有很多例外,但这里是你抛出异常的方式:
throw new IllegalArgumentException("INVALID");
Run Code Online (Sandbox Code Playgroud)
也可以,您可以创建自己的自定义例外.
编辑:还要注意例外情况.当您抛出异常(如上所述)并捕获异常时:String
可以访问您在异常中提供的异常抛出getMessage()
方法.
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
Run Code Online (Sandbox Code Playgroud)
这真的取决于你抓住它后你想要做什么.如果您需要区分异常,则必须创建自定义Exception
.否则你可以throw new Exception("message goes here");
最简单的方法是:
throw new java.lang.Exception();
Run Code Online (Sandbox Code Playgroud)
但是,您的代码中无法访问以下行.所以,我们有两种方式:
归档时间: |
|
查看次数: |
227222 次 |
最近记录: |