answersLogoWhite

0

Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.

public void myMethod(int param) throws MyException

{

if (param < 10)

{

throw new MyException("Too low!);

}

//Blah, Blah, Blah...

} The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method.

If a method is throwing an exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.

User Avatar

Wiki User

16y ago

Still curious? Ask our experts.

Chat with our AI personalities

RafaRafa
There's no fun in playing it safe. Why not try something a little unhinged?
Chat with Rafa
BlakeBlake
As your older brother, I've been where you are—maybe not exactly, but close enough.
Chat with Blake
CoachCoach
Success isn't just about winning—it's about vision, patience, and playing the long game.
Chat with Coach
More answers

The keyword throw is used to throw user defined exceptions and it requires a single argument(a throwable class object)

ex: throw new XYZException("Test");

The keyword throws is used in method signatures to declare that, this method could possibly throw an exception.

ex: public void test() throws SQLException {

}

Throwable is an interface that the Exception class implements and an interface that all user defined class would implicitly implement to ensure that they have exception like behavior..

The throw keyword is used to explicitly throw an exception.

The throws keyword is used to declare what types of exceptions are thrown by a method.

The Throwable class is the superclass of all errors and exceptions in Java.

Example:

// This class is of type Throwable

class MyClass extends Throwable {

// The main method is declared to throw a MyClass Throwable object

public static void main(String[] args) throws MyClass {

// And let's throw a new instance of MyClass to see what happens.

throw new MyClass();

}

}

Of course, this code will be pretty useless:

Exception in thread "main" MyClass

at MyClass.main(MyClass.java:6)

Java Result: 1

User Avatar

Wiki User

14y ago
User Avatar

Add your answer:

Earn +20 pts
Q: What is the difference between throw and throws in Java?
Write your answer...
Submit
Still have questions?
magnify glass
imp