Wednesday, January 22, 2025
HomeProgrammingChecked Exceptions in Java

Checked Exceptions in Java

In Java, exceptions are used to handle errors and other exceptional conditions that may occur during the execution of a program. Exceptions can be broadly categorized into two types: checked exceptions and unchecked exceptions.

Checked exceptions are exceptions that the Java compiler requires you to handle explicitly in your code. These exceptions are checked at compile-time, and failure to handle them can lead to compilation errors. In this blog post, we’ll take a closer look at what checked exceptions are, some common examples, and how to handle them in your Java programs.

What are Checked Exceptions?

Checked exceptions are exceptions that the compiler forces you to either catch or declare in the method signature using the throws keyword. This requirement is meant to ensure that these exceptions are properly dealt with and not ignored, as they usually represent recoverable conditions that a program may encounter during its execution.

When a method can throw a checked exception, the Java compiler will require you to either:

  • Catch the exception using a try-catch block.
  • Declare the exception in the method signature using the throws keyword.

The key difference between checked exceptions and unchecked exceptions (runtime exceptions) is that unchecked exceptions are not subject to the compiler’s checking, and you are not required to handle them.

Common Examples of Checked Exceptions in Java

Here is a list of some of the most common checked exceptions in Java:

  1. IOException
    • Description: IOException is thrown when an I/O operation fails or is interrupted. It is a parent class for many other I/O-related exceptions.
    • Common scenarios: File handling (e.g., when reading or writing to files), network operations, etc.
    • Example:
      import java.io.FileReader;
      import java.io.IOException;
      
      public class Example {
          public static void main(String[] args) {
              try {
                  FileReader file = new FileReader("nonexistentfile.txt");
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      
  2. SQLException
    • Description: SQLException is thrown when there is an issue with database access. This could happen due to incorrect SQL syntax, database connection problems, or other database-related issues.
    • Common scenarios: Database operations, such as querying or updating records in a relational database.
    • Example:
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      
      public class DatabaseExample {
          public static void main(String[] args) {
              try {
                  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
      }
      
  3. ClassNotFoundException
    • Description: This exception is thrown when the JVM cannot find a class that is referenced in the code. It’s typically encountered when working with Java Reflection or dynamically loading classes.
    • Common scenarios: Loading classes dynamically (using Class.forName() or similar methods).
    • Example:
      public class ClassLoaderExample {
          public static void main(String[] args) {
              try {
                  Class.forName("com.nonexistent.Class");
              } catch (ClassNotFoundException e) {
                  e.printStackTrace();
              }
          }
      }
      
  4. FileNotFoundException
    • Description: FileNotFoundException is a subclass of IOException and is thrown when an attempt to open a file fails because the file does not exist or cannot be accessed.
    • Common scenarios: Reading from or writing to a file that does not exist.
    • Example:
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.util.Scanner;
      
      public class FileExample {
          public static void main(String[] args) {
              try {
                  File file = new File("nonexistentfile.txt");
                  Scanner scanner = new Scanner(file);
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              }
          }
      }
      
  5. InterruptedException
    • Description: InterruptedException is thrown when a thread that is sleeping or waiting is interrupted before it can finish its task.
    • Common scenarios: Multi-threading and concurrency, particularly when dealing with Thread.sleep() or other waiting mechanisms.
    • Example:
      public class ThreadExample {
          public static void main(String[] args) {
              try {
                  Thread.sleep(1000);  // Sleep for 1 second
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
      
  6. ParseException
    • Description: ParseException is thrown when an error occurs while parsing a string into a date, number, or other format.
    • Common scenarios: Parsing dates or numbers from strings, such as using SimpleDateFormat.
    • Example:
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      
      public class DateExample {
          public static void main(String[] args) {
              try {
                  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                  Date date = format.parse("2021-25-12");
              } catch (ParseException e) {
                  e.printStackTrace();
              }
          }
      }
      
  7. NoSuchMethodException
    • Description: This exception is thrown when a method cannot be found that matches the provided method signature.
    • Common scenarios: Using reflection to call methods that do not exist.
    • Example:
      import java.lang.reflect.Method;
      
      public class ReflectionExample {
          public static void main(String[] args) {
              try {
                  Method method = ReflectionExample.class.getMethod("nonExistentMethod");
              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
              }
          }
      }
      

How to Handle Checked Exceptions

To handle checked exceptions, you can either use a try-catch block to catch the exception and handle it within the method or declare that the method can throw the exception by adding the throws keyword to the method signature.

See also  How can I check for NOT NULL and NOT EMPTY strings in SQL?

Example: Using try-catch

public void readFile(String filePath) {
    try {
        FileReader file = new FileReader(filePath);
    } catch (IOException e) {
        e.printStackTrace();  // Handle the exception here
    }
}

Example: Declaring the Exception with throws

public void readFile(String filePath) throws IOException {
    FileReader file = new FileReader(filePath);
}

By declaring the exception in the method signature, you are passing the responsibility of handling the exception to the caller of the method.

See also  Reading an Excel File Using Python

Conclusion

In Java, checked exceptions are a vital part of handling errors in your program. They represent exceptional conditions that are anticipated and that the programmer is expected to handle appropriately. Some common checked exceptions include IOException, SQLException, ClassNotFoundException, and InterruptedException.

Remember, whenever you’re working with APIs that throw checked exceptions, you are required to either catch them in a try-catch block or declare them using the throws keyword. This explicit handling ensures that potential issues in your code are addressed and makes your program more robust and reliable.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x