Open In App
Related Articles

Java Program to Handle Checked Exception

Improve Article
Improve
Save Article
Save
Like Article
Like

Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.

 ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.

Java Exceptions

I/O Exception: This Program throws an I/O exception because of due FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the file system, Java forces us to handle error situations where the file is not present in the given location.

Implementation: Consider GFG.txt file does not exist.

Example 1-A:

Java




// Java Program to Handle Checked Exception
// Where FileInputStream Exception is thrown
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[]) {
 
        // Reading content from file by passing local directory path
        // where file should exists
        FileInputStream GFG
            = new FileInputStream("/Desktop/GFG.txt");
 
        // This file does not exist in the location
        // This constructor FileInputStream
        // throws FileNotFoundException which
        // is a checked exception
    }
}


 Output:

Now let us do discuss how to handle FileNotFoundException. The answer is quite simple as we can handle it with the help of a try-catch block 

  • Declare the function using the throw keyword to avoid a Compilation error.
  • All the exceptions throw objects when they occur try statement allows you to define a block of code to be tested for errors and catch block captures the given exception object and perform required operations.
  • Using a try-catch block defined output will be shown.

Example 1-B:

Java




// Java Program to Illustrate Handling of Checked Exception
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws FileNotFoundException
    {
 
        // Assigning null value to object of FileInputStream
        FileInputStream GFG = null;
 
        // Try block to check for exceptions
        try {
 
            // Giving path where file should exists to read
            // content
            GFG = new FileInputStream(
                "/home/mayur/GFG.txt");
        }
 
        // Catch block to handle exceptions
        catch (FileNotFoundException e) {
 
            // Display message when exception occurs
            System.out.println("File does not exist");
        }
    }
}


Output

File does not exist

Now let us discuss one more checked exception which is ClassNotFoundException. This Exception occurs when methods like Class.forName() and LoadClass Method etc. are unable to find the given class name as a parameter.

Example 2-A

Java




// Java Program to Handle Checked Exception
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Calling the class gfg which is not present in the
        // current class temp instance of calling class
        Class temp = Class.forName("gfg");
 
        // It will throw ClassNotFoundException
    }
}


 Output:

Again now let us handle ClassNotFoundException using the try-Catch block.

Example 2-B

Java




// Java Program to Handle Checked Exception
import java.io.*;
 
// Class
class GFG {
   
    // Main driver method
    public static void main(String[] args)
        throws ClassNotFoundException
    {
        // Try block to check for exceptions
        try {
            Class temp = Class.forName(
                "gfg"); // calling the gfg class
        }
       
       // Catch block to handle the exceptions
        catch (ClassNotFoundException e) {
           
            // block executes when mention exception occur
            System.out.println(
                "Class does not exist check the name of the class");
        }
    }
}


Output

Class does not exist check the name of the class

SQLException – The SQLException is a checked exception that we need to handle explicitly.

  • The SQL exception mainly occurs during the connection of the database from Java program.

In this example, we are trying to connect the PostgreSQL database from the Java program, here everything is syntactically correct but we haven’t said to the compiler that the main method will be going to throw a SQLException. Because of this, it will give us a compile time error as shown in the below output image.

Example 3-A

Java




// Importing required classes
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
// Class
public class sql_excep {
 
    // Main driver method
    public static void main(String[] args)
    {
        Connection con
            = getConnection("javaDb", "postgres", "abrar");
    }
    public static Connection
    getConnection(String dbname, String user, String pass)
        throws SQLException
    {
        Connection con_obj = null;
       
        String url = "jdbc:postgresql://localhost:5432/";
        con_obj = DriverManager.getConnection(url + dbname,
                                              user, pass);
        if (con_obj != null) {
            System.out.println(
                "Connection established successfully !");
        }
        else {
            System.out.println("Connection failed !!");
        }
 
        return con_obj;
    }
}


Output: 

 

We can handle this in two ways.

  1. Using throws keyword at main method signature.
  2. Using try/catch block.

Example 3-B: throws

Java




// Importing required classes
 
import java.io.*;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
// Class
public class sql_excep {
     
  // Main driver method
  public static void main(String[] args)  throws SQLException
    {
        Connection con=getConnection("javaDb","postgres","abrar");
    }
   
    public static Connection getConnection(String dbname,String user,String pass) throws SQLException
    {
        Connection con_obj=null;
       
        String url="jdbc:postgresql://localhost:5432/";
       
        con_obj= DriverManager.getConnection(url+dbname,user,pass);
       
        if(con_obj!=null)
        {
            System.out.println("Connection established successfully !");
        }
        else
        {
            System.out.println("Connection failed !!");
        }
 
        return con_obj;
    }
}


Output:

 

Example 3-C: try/catch

Java




import java.io.*;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
// Class
public class sql_excep {
   
    public static void main(String[] args)
    {
        Connection con=getConnection("javaDb","postgres","abrar");
 
    }
   
    public static Connection getConnection(String dbname,String user,String pass)
    {
        Connection con_obj = null;
        String url="jdbc:postgresql://localhost:5432/";
       
      // Try block t ocheck for exceptions
      try {
            con_obj= DriverManager.getConnection(url+dbname,user,pass);
             
        if(con_obj!=null)
            {
                System.out.println("Connection established successfully !");
            }
            else
            {
                System.out.println("Connection failed !!");
            }
        }
       
        // Catch block to hanadle exceptions
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        return con_obj;
 
    }
}


Output:

 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 04 May, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials