Difference between throw and throws in Java? [duplicate] - java

This question already has answers here:
Exception handling : throw, throws and Throwable
(8 answers)
Closed 8 years ago.
Can any one clearly state the difference between throw and throws in Java exception handling with an example? I have tried googling but couldn't arrive at a conclusion. Pls help

throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.
If we see syntax wise then throw is followed by an instance variable and throws is followed by exception class names.
The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
For example
throw
throw new Exception("You have some exception")
throw new IOException("Connection failed!!")
throws
public int myMethod() throws IOException, ArithmeticException, NullPointerException {}
You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.
checked exceptions can not be propagated with throw only because it is explicitly used to throw an particular exception. checked exception can be propagated with throws.
Exception propagation: An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.
what is exception propagation?

throw use for throwing actual Exception and throws declare at method it might throws Exception.
public int findMax(int[] array) throws Exception{
if(array==null)
throw new NullPointerException(...);
...
}

public void someMethod(List<Foo> someList) throws SomeException {
if (someList.isEmpty()) throw new SomeException();
}

Related

Difference between "throw new Exception" and "new Exception"?

I am interested to know best practice to use throw new Exception() and new Exception(). In case of using new Exception(), I have seen that code moves to next statement instead of throwing exception.
But I am told that we should use new Exception() to throw RuntimeException.
Can anyone throw some light on this ?
new Exception() means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...
Consider following snippet:
public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}
private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}
}
private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}
}
the method foo() will THROW an exception if the parameter is negative but
the method foo2() will create an instance of exception if the parameter is negative
Exception e = new Exception ();
Just creates a new Exception, which you could later throw. Using
throw e;
Whereas
throw new Exception()
Creates and throws the exception in one line
To create and throw a runtime exception
throw new RuntimeException()
new Exception() means you are creating a new instance of Exception type. Which means you are just instantiating an object similar to others like new String("abc"). You would do this when you are about to throw an exception of type Exception in next few lines of code execution.
While when you say throw new Exception() this means you are saying move the program control to caller and don't execute the further statements after this throw statement.
You would do this in a situation where you find that there is no way to move ahead and execute further and hence let caller know that i can't handle this case and if you know how to handle this case, please do so.
There is no best practice as such as you are comparing oranges with apples. But remember when throwing an exception, you always throw a meaningful exception like IO has where if file is not present it throws FileNotFoundException instead of its parent IOException.

Rethrowing Exception without requiring throws Exception? [duplicate]

This question already has answers here:
Why is throwing a checked exception type allowed in this case?
(3 answers)
Closed 6 years ago.
Consider the following code:
static void main(String[] args) {
try {
} catch (Exception e) {
throw e;
}
}
This code compiles without having to add throws Exception to the method signature. (It behaves similarly with Throwable in place of Exception, too).
I understand why it can be run safely, in that Exception can't actually be thrown in the try block, so a checked exception cannot be thrown; I'm interested to know where this behaviour is specified.
It's not simply that the throw e is never reached: the following code also compiles:
static void stillCompilesWithThrownUncheckedException() {
try {
throw new NullPointerException();
} catch (Exception e) {
throw e;
}
}
But if you throw a checked exception, it doesn't compile, as I expect:
static void doesNotCompileWithThrownCheckedException() {
try {
throw new Exception();
} catch (Exception e) {
throw e; // error: unreported exception Exception; must be caught or declared to be thrown
}
}
In JLS Sec 11.2.2, it says:
A throw statement (§14.18) whose thrown expression has static type E and is not a final or effectively final exception parameter can throw E or any exception class that the thrown expression can throw.
My interpretation of this statement is that throw e can throw Exception, because the static type of e is Exception. And then, in JLS Sec 11.2.3:
It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.
But it's not a compile-time error in the first two cases. Where is this behavior described in the language spec?
Edit: having marked it a dupe, I was going to ask the follow-up question: why isn't throw e; considered unreachable in the first example.
The answer was much easier to find in JLS Sec 14.21:
A catch block C is reachable iff both of the following are true:
Either the type of C's parameter is an unchecked exception type or Exception or a superclass of Exception, or some expression or throw statement in the try block is reachable and can throw a checked exception whose type is assignable to the type of C's parameter. (An expression is reachable iff the innermost statement containing it is reachable.)
See §15.6 for normal and abrupt completion of expressions.
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
Both of these are true (it's of type Exception, and there's no earlier catch block), so it's "reachable". I guess the effort of calling out an empty try block as a special case was too great for such a marginally-useful construct.
I believe the very next paragraph of section 11.2.2 answers the question:
A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:
E is an exception class that the try block of the try statement which declares C can throw; and
…
So, throw e; “can throw” only exceptions which the corresponding try-block “can throw,” where the latter is defined by the actual statements in the try-block.
Obviously an empty try-block does not qualify as a “can throw” section for any exception class. Your second example “can throw” NullPointerException, and since the catch-block “can throw” only the exception that the try-block “can throw,” the catch-block too can throw only the unchecked NullPointerException.
Your third example’s try-block “can throw” java.lang.Exception itself, therefore the catch-block “can throw” java.lang.Exception, so java.lang.Exception must be caught or declared to be thrown.

Difference between Throw and Throws in Java- Clarification [duplicate]

This question already has answers here:
Exception handling : throw, throws and Throwable
(8 answers)
Closed 6 years ago.
I am confused to get a clear understanding of when throw is used and throws is used. Kindly provide me an example to show the difference.
Also, I tried the below code:
package AccessModifiers;
//import java.io.IOException;
public class ThrowExceptions {
int QAAutoLevel;
int QAExp;
void QAAutomationHiring(int grade)
{
if (grade<5)
throw new ArithmeticException("Not professionally Qualified");
else
System.out.println("Ready to be test");
}
void QAExperience(int x,int grade)
{
QAAutomationHiring(grade);
}
void checkThrowsExep(int a,int b) throws ArithmeticException
{
try{
int result=a/b;
System.out.println("Result is :"+result);
}
catch(Exception e)
{
System.out.println("The error messgae is: "+ e.getMessage());
}
}
public static void main(String args[])
{
ThrowExceptions t=new ThrowExceptions();
//t.QAAutomationHiring(8);
t.QAExperience(2,8);
t.QAExperience(4,2);
t.checkThrowsExep(5, 0);
}
}
In the above code, when I run the program, the line- 't.checkThrowsExp' in main function is not reached. I studied that throw and throws are used to catch the exception and continue with the program execution. But here the execution stops and not proceeding to the next set of statements. Please share your comments.
throws is used to tell people that
Warning: this method/constructor has a high chance of throwing XXXException and YYYException! Please make sure you handle them!
Example:
The Thread.sleep method is declared as:
public static native void sleep(long millis) throws InterruptedException;
As you can see, the throws keyword tells people that sleep is very likely to throw an InterruptedException. Because of this, you must surround the method call with try-catch or mark the caller method with throws InterruptedException. The exceptions after the throws keyword are usually "checked" exceptions which are caused by invalid conditions in areas outside the immediate control of the program, like invalid user inputs, database problems etc.
Please note that it is possible for a method marked with throws XXXExcepion to never throw XXXException.
throw, on the other hand, actually throws the exception. It can be used like
throw new RuntimeException("Something went wrong!");
And whenever code execution reaches this statement, an exception will be thrown no matter what, and the method returns.
In short, throw actually does the throwing, and throws is only saying that an exception will likely be thrown (which in fact, be wrong).
Throw actually returns the exception whereas throws is a sign to the compiler, that this method could return an exception.
In your code above the exception ArithmeticException will be created and returned, if the grade is lower than 5, which is the case in your second call of QAExperience.
As the calling method called the method, which returned the exception, is not insede a catch block it will also just stop its execution and return to the main method. As the main method also does not catch the exception it will just like the others stop its execution and return the exception. This is the reason, why t.checkThrowsExp will not be executed.

Is it necessary to use "throws" whenever we use "throw"?

Assuming that the Exception we are throwing is checked, is it compulsory to add throws in a method declaration whenever we use throw inside the method?
Any checked exception (e.g., one which does not extend RuntimeException) that might escape a method needs to be declared in the method signature. For example:
public static void mightThrow(String s) throws NumberFormatException {
// ...
int x = Integer.parseInt(s);
// ...
}
Even though we do not throw any exceptions directly, Integer.parseInt() might throw a checked NumberFormatException. Since we call that method, and we do not catch the potential exception, then our method must also declare the exeception in its throws signature.
This does not necessarily mean that every method that throws (or might throw) a checked exception must declare throws in its signature. If the thrown exception is always caught within that method, it need not be added to the signature. For example:
public static Integer tryParseInteger(final String s) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ignored) {
return null;
}
}
In this example, we will always catch any NumberFormatException that might be thrown by Integer.parseInt() and prevent it from bubbling up the stack, so we do not need to declare it in our tryParseInteger() method.
Unchecked exceptions never need to be declared:
public static void unsupported() {
throw new UnsupportedOperationException(
"The specified operation is not supported."
);
}
Here, because UnsupportedOperationException derives from the unchecked RuntimeException, it does not need to be declared.
No, since you may want to throw a exception but handle it in the same place, aka method
The Throws simply let javac know that this method might cause this kind of exception. It is not always necessary. It's useful when you know that a specific method can throw some sort of exception.
Generally speaking, Java is exception-strict, so you have to specific what types of exceptions a method throws. Note that you can use inheritance to simplify your methods' signatures. E.g., you can declare your method as throws IOException, and within its implementation throw any type of IOException you want such as FileNotFoundExeption, InteruptedIOException, etc.
One exception (no pun intended) to this rule are RuntimeExceptions (such as OutOfMemoryError or UnsupportedOperationException) which can be thrown without having to declare them.
Differences:
1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").
2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method
signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
private static boolean shutdown() {
throw new UnsupportedOperationException("Not yet implemented");
}
as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.
static{
try {
throw new Exception("Not able to initialized");
} catch (Exception ex) {
Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
4) throw keyword can also be used to break a switch statement without using break keyword.
int number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}

Throws and Throw in Exception handling [duplicate]

This question already has answers here:
Exception handling : throw, throws and Throwable
(8 answers)
Closed 9 years ago.
can anyone brief about difference between throws and throw in Exception handling in Java
throws was used when your method have some code which cause the error at run time and you need to handle or throws that exception when your method was calling.
While throw was for you can explicitly throw an error.
here is the example for both
For throws
public void test() throws ClientProtocolException,IOException{
HttpGet httpGet = new HttpGet(urlStr);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpGet);
}
this will throws the exception as ClientProtocolException or IOException whenever it cause.
For throw
public void test(String str){
if(str==null){
throw new NullPointerException(); // now here you explicitly throws the error whenever you getting str object as null
}
}
When we say: function() throws IOException, it means that the code inside the function is capable of throwing an IOException. So whoever is calling this function should handle this function in a try-catch block. So here we see the concept of checked exceptions. When we say: throw IOException. Your code-block is deliberately throwing this exception and someone needs to catch it.
throws : It simply passes the exception to the caller method. Also is an indicator that the method has possibility of throwing some exception while running, like IOException, SQLException etc... In case of checked exception (anything other than RunTimeException or its subclass) It becomes mandatory to handle (try-catch) or again pass to caller.
throw: it is the clause to generate the exception. (in simple words ) It is the reason why you see throws in method signature, because they must have any throw declaration inside them
We use throws in a method signature to indicate that a method is capable of throwing a particular exception. Any code calling this method will have to deal with the possibility that particular exception can occur.
The throw keyword is used to actually throw an exception. It can be used wherever you can place a statement.

Categories

Resources