throw
and throws
are the keywords in java which are related to the concept of exception handling in java.
This post will explain the meaning and use of these keywords in detail.
In order to understand these keywords, you must be aware with exception handling using try-catch
block in java.
throw
keyword is used to deliberately throw an exception from a program. In order to throw the exception, throw
keyword is followed by the exception object.The exception to be thrown may be an existing exception caught by a catch block or an exception object created using
new
keyword.
Syntax of throw
when used to throw an already raised exception is
try {
// statements
} catch(Exception e) {
throw e;
}
Syntax of throw
for throwing a new exception is
try {
// statements
} catch(IOException e) {
throw new Exception(e);
}
Exception propagation using throw
When an exception is thrown using
throw
, the program execution does not move forward and returns back to the calling code.
If the calling code has handled the exception, then the control moves to the catch
block but if the calling code has not handled the exception, then the control moves further up towards the calling code till it finds the exception handler.
If there is no exception handler, then the program terminates. An example will make it more clear.
Suppose main
method calls methodA, which in turn calls methodB and methodB calls methodC.
Now methodC throws an exception at line 20.
No code after line 20 of methodC will be executed and the control will move back to methodB.
If methodC was called from within a try-catch
block from methodB, then the control will be transferred to the catch
block of methodB.
If there was no try-catch
block in methodB, then the control will move up to methodA and so on till an exception handler is not found.
In case no exception handler is found till the topmost point, then the exception is handled by the JVM’s default exception handler which prints the entire exception stack trace.
throw example
Following is an example of using throw
keyword in java.
public class ThrowExceptionDemo { static void readFile() throws Exception { try { // create a new writer object FileWriter wr = new FileWriter(new File("x:/abc.txt")); wr.write("Test content"); wr.close(); } catch (IOException e) { // throw exception if the exception is due to wrong path if(e.getMessage().contains("cannot find the path")) { throw new Exception("Invalid path"); } // throw the generated exception throw e; } } public static void main(String[] args) { try { readFile(); } catch (Exception e) { // catch exception raised from readFile method System.out.println(e.getMessage()); } } }
Above code example contains a method which writes a string to a file.
Exception while writing is handled and catch
block checks if the error is due to invalid path, then throw a new exception else throw the actual exception.
Path of the file to be written has been voluntarily made invalid so that new exception object is thrown and is caught by the calling method where exception message is printed.
Following is the output.
Invalid path
Notice how the invocation of readFile
method is surrounded by try-catch
block inside main
method and the above error is printed from the catch
block of main
method only.
This is how the exception propagates up as explained in the last section.
As stated earlier,
throw
is used to throw an exception from some point in the application. But what is the benefit of using throw
.Following is the reason of using throw keyword:
throw is used to terminate program execution
Many times if an exception occurs, there is no point in continuing execution.
Example, you have to read a file, display its contents and then make a copy of this file by writing the contents to a new file.
If the source file does not exist, there is no point in moving forward with other operations.
In such scenarios, throw
is used to prevent execution from moving forward.
Example,
File fileToRead = new File(“D:/source.txt”);
// check if file to be read is present
if (!fileToRead.exists()) {
// return from here only
throw new FileNotFoundException(“File does not exist”);
}
// file reading code
throws keyword in java
If a method raises some exception, then it should handle it inside its body using try-catch
block.
If it does not want to handle the exception itself and wants the calling code to handle it, then it should declare that it will throw an exception and the code that calls this method should take care of handling the exception.
For declaring that a method will throw an exception, throws
keyword is used followed by the name of exception as shown below.
public void deleteData throws SQLException {
// code for data deletion
}
If a method throws an exception and it does not handle it nor it declares that it will throw the exception, then there will be compiler error.
A method may declare to throw any number of exception with a single throws
keyword followed by names of exception separated by comma.
Example,
public void addData throws SQLException, NoSpaceException, PermissionException {
// code for data addition
}
Remember that this is valid only for checked exceptions.
That is, a method should declare that it throws an exception only if the exception thrown is a checked exception.
If the exception is unchecked, then there is no need to handle it or declare it.
A method may declare it but it is not necessary.
There are many methods in java api which declare that they will throw an exception such as
- constructor of
java.io.FileReader
class. getConnection
method fromjava.sql.DriverManager
readLine
method fromjava.io.BufferedReader
etc.
throws example
Taking the example demonstrated in throw
keyword, if we remove the try-catch
block in readFile
method, then the code will be modified as below.
public class ThrowExceptionDemo { static void readFile() throws IOException { // create a new writer object FileWriter wr = new FileWriter(new File("x:/abc.txt")); wr.write("Test content"); wr.close(); } public static void main(String[] args) { try { readFile(); } catch (Exception e) { // catch exception raised from readFile method System.out.println(e.getMessage()); } } }
Notice that now readFile
method does not handle the exception but it declares it using throws
.
Code that calls this method(main
method in this case) has handled the declared exception in try-catch
block.
If the calling code also does not handle it, then it needs to declare in its signature.
Thus, in that case signature of main
method will look as
public static void main(String[] args) throws IOException { }
Polymorphism in throw and throws
Till now it should have been clear that you throw an exception using throw
keyword while throws
is used to declare that some exception might be thrown.
If a method declares to throw an exception, then obviously it would be throwing some exception.
An important point to remember is that the type of exception that is actually being thrown should be of the same type as that declared using throws
or its sub-type.
That is,
if a method declares to throw java.io.IOException
, then it can throw an object of java.io.IOException
or its sub-type such as java.io.FileNotFoundException
etc.
It can not throw java.sql.SQLException
or java.lang.Exception
.
Thus, polymorphism is present here also.
Difference between throw and throws
After learning about the meaning and usage of both the keywords, it is time to know about throw vs throws pointers given below
throw | throws |
throw is used for throwing an exception |
throws is used for declaring that a method may throw an exception. |
With throw , program execution can be terminated based on a condition. |
throws can only be used to notify the calling code that a method might throw an exception. |
With throw , you can throw a single exception at a time. |
throws can declare multiple exceptions separated by a comma. |
throw is used inside a method or constructor body. |
throws is used in the signature of method or constructor. |
throw is followed by an actual exception object. |
throws is followed by the name of exception. |
If you found this post useful, then do not forget to hit the clap button below.