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; } } }
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?
As you've seen, Java offers you two general types of exceptions: The checked and the unchecked exception. You should use a checked exception for all exceptional events that can be expected and handled by the application. You need to decide if you want to handle it within a method or if you specify it.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
How to throw an exception. To throw an exception, we generally use the throw keyword followed by a newly constructed exception object (exceptions are themselves objects in Java). Most exception constructors will take a String parameter indicating a diagnostic message.
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");
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With