Difference between throw and throws in java - Java @ Desk

Thursday, May 23, 2013

Difference between throw and throws in java

The throw keyword is used to force or throw an exception to the caller of the method. Throw keyword is used inside the method to throw any type of exception with the customized error message.

Throws keyword is used in the method declaration. Throws keyword actually throws that type of exception which is not handled by the method definition. For example, a method is doing some database connection and is not surrounded by try/catch block, so this method throws SQLException. The throws clause tells the compiler that this particular exception would be handled by the calling method.




public String getPersonLocation(String employeeNumber) throws SQLException {

Connection connection = null;
PreparedStatement fielStatement = null;
try {
// This method returns a database connection and throws SQLException.
//And this will be handled by this try catch block. connection = getConnection();
}
catch (SQLException e) {
if (connection != null) {
// This code in actual throws the SQLException,
//but since this code is not handled by this method,
//we are throwing SQLException in method signature
connection.close();
}
e.printStackTrace();
throw e;
}
return null;
}






No comments:

Post a Comment