Java8 | Exception Handling

Hasan Kadir Demircan
2 min readDec 16, 2021

--

Exception Hierarchy

As you know, we continue to investigate Java8 features. That’s why today’s subject is Exception Handling.

MultiCatch Exception

  • This feature came from Java7.
  • If we want to use multi-catch, you need to pay attention to the IS-A relation. Because we can not use these relations.
  • For example, FineNotFoundException IS-A IOException.
try {
}
catch (FileNotFoundException | IOException e) { }
// DOES NOT COMPILE
  • We can not set variables for all Exceptions.
catch(Exception1 e | Exception2 e | Exception3 e) 
// DOES NOT COMPILE
catch(Exception1 e1 | Exception2 e2 | Exception3 e3)
// DOES NOT COMPILE
catch(Exception1| Exception2| Exception3 e)
// COMPILES

Before Java7, we were using like below.

After Java7, we have started to use like below.

Try With Resource

  • This feature came from Java7.
  • When we work on files, sometimes we could forget to close the file.
  • This approach will close the file stuff after does process.
try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName));
FileInputStream fileIn = new FileInputStream(fileName)) {
//
}
  • In order for us to use it, the class must be auto closeable.
package java.lang.AutoCloseable;

Before Java7, we were using like below.

After Java7, we have started to use like below.

AutoCloseable Example;

Suppressed Exception

  • This feature came from Java7.
  • We’ve already discussed the try-with-resources block. What we have not discussed are suppressed exceptions. In a try-with-resources statement, there might be more than one exception that could get thrown; for example, one within the try block, one within the catch block, and another one within the finally block. However, only one exception can be caught(the code in the try block), so the other exception(s) will be listed as suppressed exceptions. From a given exception object, you can use the method getSuppressed() to get the list of suppressed exceptions.

Let’s look at the example,

Output:

try block!!
Shut down...
catch block!
/ by zero
  • As we see the output, we missed the “Exception in close” exception.
  • So, if we add this code block, we will catch all errors.
for(Throwable t : e.getSuppressed()){
System.out.println(t.getMessage());
}

Github: Exception Handling

--

--

Hasan Kadir Demircan
Hasan Kadir Demircan

No responses yet