what is the use of throws keyword rather than


What is the use of throws keyword ?

Rather than explicitly catching an exception you can declare in which your method throws the exception. This passes the repsonsibility to handle it to the method in which invokes your method. This is done with the throws keyword. For instance,
public static void copy(InputStream in, OutputStream out)
throws IOException {

byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}

}
A single method may have the potential to throw more than one kind of exception. In this case the exception clases are just separated through commas. For example,
public BigDecimal divide(BigDecimal value, int roundingMode) throws ArithmeticException, IllegalArgumentException

You can declare in which your method throws runtime exceptions though you do not have to. The major use of this is as documentation for the programmer. It can also be useful in white box testing.

 

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: what is the use of throws keyword rather than
Reference No:- TGS0284900

Expected delivery within 24 Hours