In Java, all exceptions are divided into two groups:
- Checked
- Unchecked
If a class isn't a subtype of RuntimeException and it inherits the Exception class, then this class belongs to checked exceptions. If a function throws checked exceptions, then we have to wrap its invoking into the try { ... } catch { ... } finally { ... } block. The finally block can be omitted.
The following example contains the main function that creates a new instance of the FileInputStream class:
public class Example2 {
public static void main(String[] args) {
new FileInputStream("invalid/path");
}
}
Since a constructor of FileInputStream throws FileNotFoundException, we can't compile this code. IntelliJ IDEA shows the following tip:
To fix this error, we can surround this code with a try { ... } catch { ... } finally { ... } block, or add an exception to the method signature. If you use try { ... } catch { ... } finally { ... }, an implementation may look like this:
public static void main(String[] args) {
try {
new FileInputStream("invalid/path");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
In the second case, if we use the throws keyword, it may look like this:
public static void main(String[] args) throws FileNotFoundException {
new FileInputStream("invalid/path");
}
The following code throws NullPointerException, because the value reference is null:
public static void main(String[] args) {
Integer value = null;
value.hashCode();
}
However, we don't have to handle this exception because it's unchecked.