The simple and major difference between "throws" and "throw" is that "throws" is used when declaring a method, where "throw" is inside the method.
Now InvalidStringException here is a user-defined exception. In fact it can be any "checked" exception. User-defined exceptions are checked exceptions. The other type of exceptions is unchecked or runtime. It is unusual to throw runtime exception unless it is necessary.
K. Tsang wrote:The simple and major difference between "throws" and "throw" is that "throws" is used when declaring a method, where "throw" is inside the method.
. . . . User-defined exceptions are checked exceptions. . . . .
That is not correct. User‑defined Exceptions can be checked or unchecked, depending on their inheritance hierarchy.
Never write thisThat has two disadvantages.
1: That Exception is a very inefficient way to implement an if-else.
2: Code which uses that foo() method has no way of knowing whether anything has gone wrong.
The idea of checked Exceptions particularly is that code can attempt to recover from them. So you reduce the foo method to this:-If boo happens, then that method will create and throw an XYZException object. If that is checked, then the compiler needs to know that every method using foo() will deal with that exception.
So there are two ways to deal with an Exception: catch it, or let a calling method deal with it. We have already seen that it is better for the Exception to be dealt with elsewhere from where it was created. If you use the throws keyword, like this… then the compiler “knows” that every method calling foo() will know about the Exception.
This is called “catch or specify”. One of the best places to read about this is the Java Tutorials.
Joined: Nov 10, 2008
Thanks Tsang and Campbell ,i have understood about the usage of throw clause from Java Tutorials by referring to your explanations