How do I use the throws keyword to declare method exceptions?

The 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.

package org.kodejava.basic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ThrowsExample {
    public static void main(String[] args) {
        Connection connection = null;

        try {
            // Might throw ClassNotFoundException or SQLException
            // that's why we should catch them.
            connection = getConnection();
        } catch (ClassNotFoundException | SQLException e) {
        } finally {
            System.out.println("Finally is always executed");
            System.out.println("Close connection");
            try {
                if (connection != null && !connection.isClosed()) {
            } catch (SQLException e) {
                System.out.println("Sql exception caught");

     * Get database connection.
     * @return Connection
     * @throws ClassNotFoundException when driver class is not found.
     * @throws SQLException           when database error occurs.
    private static Connection getConnection()
            throws ClassNotFoundException, SQLException {

        return DriverManager.getConnection("jdbc:mysql://localhost/kodejava",
                "root", "");

Without adding the database driver it will get the following exception:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(
    at java.base/java.lang.ClassLoader.loadClass(
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(
    at org.kodejava.basic.ThrowsExample.getConnection(
    at org.kodejava.basic.ThrowsExample.main(
Finally is always executed
Close connection

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.