In this lesson, you will learn
Beginning with JDK 7, three interesting and useful features have been added to the exception system.

It automates the process of releasing a resource, such as a file, when it is no longer needed. It is based on an expanded form of the try statement called try-with-resources.
It will be discussed in the next chapter i.e. file handling – try-with-resource
Syntax
Here is a catch statement that uses the multi-catch feature to catch both ArithmeticException and ArrayIndexOutOfBoundsException:
catch(ArithmeticException | ArrayIndexOutOfBoundsException e) { }
In Java, the “final rethrow” or “more precise rethrow” feature introduced in JDK 7 enhances the way exceptions can be handled, particularly when rethrowing exceptions caught by a multi-catch block.
Before Java 7, when you caught an exception and wanted to rethrow it, you had to either handle it or declare the method as throwing the most general type of exception caught in the catch block. This often led to a situation where the throws clause of a method was more general than necessary.
With JDK 7, the compiler tracks the precise types of exceptions thrown within a try block. This allows you to rethrow the exception in a catch block while only declaring the specific checked exceptions that might actually be thrown, rather than a broader exception type.
If you wanted to rethrow an exception while possibly adding additional handling, you would need to declare the method to throw the general Exception type if you were not sure of the specific exception types.
public void processFile(String path) throws Exception {
try {
// Code that might throw IOException or SQLException
} catch (Exception e) {
// Additional handling or logging
throw e; // Must throw Exception
}
}
With Java 7, you can catch the exception and rethrow it while only declaring the specific exceptions that your try block can actually throw.
public void processFile(String path) throws IOException, SQLException {
try {
if (path == null) {
throw new IOException("File path cannot be null");
}
// Assuming there's database interaction that could throw SQLException
if (path.isEmpty()) {
throw new SQLException("Database access error");
}
} catch (final IOException | SQLException e) {
// Handle specific exceptions, for example, log them
System.err.println("Error processing file: " + e.getMessage());
throw e; // Precise rethrow: Only declares IOException and SQLException
}
}
IOException and SQLException can be separately caught and handled. The rethrow in the catch block allows you to throw the same exception without having to declare it as a broader type.
This precise rethrow capability simplifies exception handling by making it cleaner and more specific, which in turn helps maintain clearer and more robust code.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.