Throws and Throw in Java are two important key words . These key words are significant in exception handling .If an exception occurred in a method and if it is not handled in that method , we can throw the exception to the point where that particular method is invoked . This can be achieved by using throw or throws key words.
Throws and Throw in Java
1.throws key word
The throws key word is using with the method signature.Followed by the throws key word the Exception type also needs to be specified.Suppose our method doSomething() throws InterruptedException then the method will be like this:
public void doSomething() throws InterruptedException{
//Method body
}
If our method throws more than one type of Exception , then all those exceptions can be mentioned in the method signature . Suppose in our doSomething() method throws InterruptedException and IOException then the method will be like this:
public void doSomething()throws InterruptedException,IOException{
//Method body
}
The concept of throws key word can be well understood with the help of an example.
Our code reads a string value from key word using BufferedReader object.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThrowsSample {
public ThrowsSample() {
}
public void readData() throws IOException {
System.out.println("Enter any string");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String string = bufferedReader.readLine();
System.out.println("Entered data = " + string);
}
public static void main(String[] args) {
ThrowsSample sample = new ThrowsSample();
try {
sample.readData();
} catch (IOException io) {
io.printStackTrace();
}
}
}
The readLine() method implementation of BufferedReader class throws IOException.We can put try/catch block around the readLine() method to handle the exception. Here we used throws keyword to send the exception to the higher level. The main method calls the readData() method.So the main should catch the exception.
2.throw key word
throw key word is used to throw an exception from a method body .Let us explain this with an example.Our application simply throws an Exception and the main method is catching and handling the exception.
public class ThrowSample {
public ThrowSample() {
}
public void getException() throws Exception{
System.out.println("Throwing exception");
throw new Exception();
}
public static void main(String[] args) {
ThrowSample sample = new ThrowSample();
try{
sample.getException();
}catch (Exception e){
e.printStackTrace();
}
}
}