如何在Java中抛出一般异常? [英] How to throw a general exception in Java?

查看:100
本文介绍了如何在Java中抛出一般异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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){
//抛出异常
} else {
speed - = decrement;
}
}
}

HelloWorld.java: / p>

  public class HelloWorld {

/ **
* @param args
* /
public static void main(String [] args){

Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();

//做某事

//打印有用的东西,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); 


Consider this simple program. The program has two files:

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;
        }
    }
}

And 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());
    }

}

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);
  }

}

In your code:

throw new InvalidSpeedException("TOO HIGH");

这篇关于如何在Java中抛出一般异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆