Java programs handling of checked exceptions.

Java programs handling of checked exceptions.

Here are five Java programs that demonstrate the handling of checked exceptions, along with step-by-step explanations for each (Java programs handling of checked exceptions.)

Program- “1” : File Not Found Exception 

java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileNotFoundExample {
    public static void main(String[] args) {
        File file = new File("nonexistent.txt");
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Explanation:
1. Import Classes: We import File, FileNotFoundException, and Scanner from java.io and java.util.
2. Create File Object: A File object is created that points to “nonexistent.txt”, which does not exist.
3. Try Block: We attempt to open the file using Scanner. This can throw a FileNotFoundException, a checked exception.
4. Catch Block: If the exception is thrown, we catch it and print an error message.

Program- “2” : SQL Exception

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

public class SQLExceptionExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String user = "username";
        String password = "password";

        try {
            Connection connection = DriverManager.getConnection(url, user, password);
            Statement statement = connection.createStatement();
            statement.executeUpdate("INSERT INTO users_data (username) VALUES ('code pulling')");
            connection.close();
        } catch (SQLException e) {
            System.out.println("SQL Exception: " + e.getMessage());
        }
    }
}

Explanation:
1. Import Classes: We import necessary SQL classes.
2. Database Connection: We define the URL, username, and password for the database connection.
3. Try Block: Inside a try block, we attempt to establish a connection to the database and execute an SQL statement.
4. Catch Block: If any SQLException occurs (like wrong credentials), we catch it and print the message.

Program- “3” : Class Not Found Exception

java
public class ClassNotFoundExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.nonexistent.ClassName");
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found: " + e.getMessage());
        }
    }
}

Explanation:
1. Try to Load Class: We attempt to load a class that doesn’t exist using Class.forName().
2. Catch Block: If the class is not found, a ClassNotFoundException is thrown and caught, allowing us to handle the error gracefully.

java
public class InterruptedExceptionExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Thread woke up!");
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted: " + e.getMessage());
            }
        });

        thread.start();
        thread.interrupt(); // Immediately interrupt the thread
    }
}

Program-“4”: Interrupted Exception.

java
public class InterruptedExceptionExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Thread woke up!");
            } catch (InterruptedException e) {
                System.out.println("Thread was interrupted: " + e.getMessage());
            }
        });

        thread.start();
        thread.interrupt(); // Immediately interrupt the thread
    }
}

Explanation:
1. Thread Creation: We create a new thread that sleeps for 1 second.
2. Try Block: Inside the thread, we handle InterruptedException if the thread is interrupted during sleep.
3. Interrupt the Thread: The main method interrupts the thread right after it starts.
4. Catch Block: If interrupted, the exception is caught and a message is printed.

Program- “5” : Parse Exception

java
public class ParseExceptionExample {
    public static void main(String[] args) {
        String number = "123a";

        try {
            int result = Integer.parseInt(number);
            System.out.println("Parsed number: " + result);
        } catch (NumberFormatException e) {
            System.out.println("Number format exception: " + e.getMessage());
        }
    }
}

Explanation:
1. String to Parse: We define a string that cannot be converted to an integer.
2. Try Block: We try to parse the string using Integer.parseInt().
3. Catch Block: If it throws a NumberFormatException, we catch it and print an appropriate message.

These programs illustrate how to handle various checked exceptions in Java, showing the importance of managing errors effectively to create robust applications.

Leave a Reply

Your email address will not be published. Required fields are marked *