Richard Knop Richard Knop - 10 days ago 5
Java Question

How to throw a general exception in Java?

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?

Answer

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