Difference between throw and throws keyword on Exception handling in Java is a popular core java interview question. Exception handling being an important part of Java programming language, complete knowledge of all keywords related to exception handling e.g. try, catch, finally, throw and throws is important. Main difference between throw and throws is in there usage and functionality. where throws is used in method signature to declare Exception possibly thrown by any method, throw is actually used to throw Exception in Java code, here is an example of both throw and throws keyword which makes it easy to understand difference between them.
public void shutdown() throws IOException{
throw new IOException("Unable to shutdown");
}
if you see the code above, throws keyword is used to declare Exception thrown by this method shutdwon(), by looking at method signature we know that its throwing IOException. while inside method code throw keyword is actually used to throw instance of IOException. here are couple of more differences between throw and throws keyword in java:
Difference between throw and throws in Exception handling - Java Example
1) You can declare multiple exceptions thrown by the 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 the method signature, a method suggesting its caller to prepare for Exception declared in the throws clause, especially in case of checked Exception and provide sufficient handling of them.
On the other hand, throw keyword transfer control of execution to the caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in the below example:
On the other hand, throw keyword transfer control of execution to the caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in the below example:
private static boolean shutdown() {
throw new UnsupportedOperationException("Not yet implemented");
}
as in the below method shutdown should return boolean but having throw in place compiler understand that this method will always throw an exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside a method or static initializer block provided sufficient exception handling as shown in the 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 as shown in below example:
int number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}
We have seen differences between throw and throws in Java and they should be used accordingly. Let me know if you come across any other difference on throw vs throws in java.
Other Java Tutorials you may like
- How to Convert Map into List in Java
- Difference between Thread and Runnable in Java
- How to parse XML Files in Java using DOM parser
- How to use Factory Design pattern in Java
- How to find the current Date in Java with Example
- How SubString works in Java
- How to Convert Enum to String in Java
- Difference between ArrayList and LinkedList in Java
That's all about the difference between throw and throws in Java. Now that you know the fundamental difference,e you should be able to use them in the correct place. If you have any questions or feedback, please drop a note.
throw vs throws, throw and throws in Java, throws vs throw in Java, throw vs throws in Java, difference between throw and throws in Java, difference between throw and throws, what are differences between throw and throws, when to use throw and when to use throws in Java
ReplyDeleteCan you please give an example of throw and throws, to understand difference between them better ? My understanding of throw is very limited but I know we can also use throw not just to throw exception but also to return from method or switch block.
ReplyDeleteCan we throw Errors in Java ? like throw java.lang.OutOfMemroyError etc
ReplyDelete'throws' is always used with a method and specifies this method may raise given exception(exception name followed by keyword throws)..
ReplyDeletethrow is used to raise an exception manually..
how is message is print in the custom exception??
ReplyDeleteas we didnt use System.out.println??
Throw is used create custom exception
ReplyDeleteCan anyone please explain the diff....i still dont understand
ReplyDeletecan anyone please briefly explain the difference between throw and thrown..... still i can't understand...
ReplyDeleteI know that, error and exceptions are the problems in java coding, then why we generate Exceptions manually using this 'throw' keyword?
ReplyDeleteimport java.io.IOException;
ReplyDeleteclass Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
In exceptional handling throw keyword is best used only for checked exceptions
ReplyDeleteie compile time exceptions
throw keyword doesnot handle runtime exceptions like ArithmeticException etc.
throw keyword will throw the said exception and stops where as try catch methods will handle runtime exceptions and continues
the regular
flow of the program
throws keyword is used declare exceptions so that if there any exceptions ocuurring during the coding the compile will
prompt us saying please handle the exception
simply speaking throws keyword is like an alarm!!
number 3 does NOT make sense...are you missing some words in that sentence. Sounds "run-off"ish
ReplyDeletePlease anyone can explain me how throw keyword is used to break switch statement
ReplyDeleteint number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}
@Tushar, throw return the control back to the caller, acting like a break in the switch statement. In your example, if you pass 1 or 2 then they will throw Exception, since you don't have default case, nothing will happen if you pass any number other than 1 and 2.
ReplyDeleteVery nice & perfect explanation. . Thanks
ReplyDelete