java checked exception

java checked exception

In Java, a checked exception is an exception that is checked at compile time. This means that if a method declares that it throws a checked exception, the calling code must either handle the exception using a try-catch block or declare that it throws the exception itself.

Here's an example of a method that declares that it throws a checked exception:

refer‮al:ot ‬utturi.com
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void readFile(String fileName) throws FileNotFoundException, IOException {
    FileReader reader = new FileReader(fileName);
    try {
      // read from the file
    } finally {
      reader.close();
    }
  }
}

In this example, the readFile method declares that it throws two checked exceptions, FileNotFoundException and IOException. If the calling code wants to handle these exceptions, it must include a try-catch block to catch the exceptions. If the calling code does not want to handle the exceptions, it must declare that it throws the exceptions itself.

For example, here's how the calling code can handle the exceptions using a try-catch block:

import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try {
      Main.readFile("/path/to/file");
    } catch (FileNotFoundException e) {
      // handle FileNotFoundException
    } catch (IOException e) {
      // handle IOException
    }
  }
}

And here's how the calling code can declare that it throws the exceptions itself:

import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws FileNotFoundException, IOException {
    Main.readFile("/path/to/file");
  }
}

Checked exceptions are used in Java to enforce the handling of exceptions that are likely to occur at runtime, such as file not found or input/output errors. These exceptions are typically recoverable, and it is expected that the calling code will handle them in a way that allows the program to continue executing.

On the other hand, unchecked exceptions, also known as runtime exceptions, are not checked at compile time and do not need to be declared or handled by the calling code. These exceptions are typically used to indicate programming errors that cannot be recovered from, and are usually thrown by the Java runtime itself. Examples of unchecked exceptions include NullPointerException and IndexOutOfBoundsException.

Created Time:2017-11-03 00:14:49  Author:lautturi