How to use the throws keyword to declare method exceptions?
throws keyword is used in method declarations to specify which exceptions are not handled within the method body but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of
RuntimeException must be declared using the throws keyword.
In the example below you could see that the
getConnection() method can cause a
ClassNotFoundException when the driver class cannot be found and an
SQLException when it fails to initiate a connection to database.
On the other end, the
main() method which call the
getConnection() method should catch all the exception throws by the
getConnection() method in its body.