The throws statement
We have to deal with SQLException
because it is a checked exception, and the getConnection()
, createStatement()
, executeQuery()
, and next()
methods declare it in their throws
clause. Here is an example:
Statement createStatement() throws SQLException;
This means that the method’s author warns the method’s users that it might throw such an exception, forcing them to either catch the exception or to declare it in the throws
clause of their methods. In our preceding example, we have chosen to catch it using two try...catch
statements. Alternatively, we can list the exception in the throws
clause and, thus, remove the clutter by effectively pushing the burden of the exception handling onto the users of our method:
void throwsDemo() throws SQLException {
Connection conn =
DriverManager.getConnection("url","user","pass");
...