How can I throw a general exception in Java?

JavaException

Java Problem Overview


Consider this simple program. The program has two files:

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

}

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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

You could use IllegalArgumentException:

public void speedDown(int decrement)
{
    if(speed - decrement < 0){
        throw new IllegalArgumentException("Final speed can not be less than zero");
    }else{
        speed -= decrement;
    }
}

Solution 3 - Java

Well, there are lots of exceptions to throw, but here is how you throw an exception:

throw new IllegalArgumentException("INVALID");

Also, yes, you can create your own custom exceptions.

A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.

try{
    methodThatThrowsException();
}catch(IllegalArgumentException e)
{
  e.getMessage();
}

Solution 4 - Java

It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");

Solution 5 - Java

The simplest way to do it would be something like:

throw new java.lang.Exception();

However, the following lines would be unreachable in your code. So, we have two ways:


  1. Throw a generic exception at the bottom of the method.
  2. Throw a custom exception in case you don't want to do 1.

Solution 6 - Java

Java has a large number of built-in exceptions for different scenarios.

In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.

Solution 7 - Java

You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.

The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.

Solution 8 - Java

It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichard KnopView Question on Stackoverflow
Solution 1 - JavaFortegaView Answer on Stackoverflow
Solution 2 - JavaMaurício LinharesView Answer on Stackoverflow
Solution 3 - JavaRMTView Answer on Stackoverflow
Solution 4 - JavaVladView Answer on Stackoverflow
Solution 5 - JavaSudip BhandariView Answer on Stackoverflow
Solution 6 - JavaSLaksView Answer on Stackoverflow
Solution 7 - JavaomnomnomView Answer on Stackoverflow
Solution 8 - JavaAbimaran KugathasanView Answer on Stackoverflow