Suppressed Exception Example

This program demonstrates suppressed exceptions in try-with-resources.

Problem Statement

Write a Java program that shows suppressed exceptions when closing resources.

Source Code

1 import java.io.*;
2 public class SuppressedExceptionExample {
3 public static void main(String[] args) {
4 System.out.println("Eduinq Suppressed Exception Example");
5 try(MyResource r=new MyResource()) {
6 throw new Exception("Eduinq Primary Exception");
7 } catch(Exception e) {
8 System.out.println("Eduinq Exception: "+e.getMessage());
9 for(Throwable t:e.getSuppressed()) {
10 System.out.println("Eduinq Suppressed: "+t);
11 }
12 }
13 }
14 }
15 class MyResource implements AutoCloseable {
16 public void close() throws Exception {
17 throw new Exception("Eduinq Closing Exception");
18 }
19 }

Program Output

					Eduinq Suppressed Exception Example
Eduinq Exception: Eduinq Primary Exception
Eduinq Suppressed: java.lang.Exception: Eduinq Closing Exception
				

Explanation

Suppressed exceptions occur when multiple exceptions are thrown. - Primary exception is preserved, secondary is suppressed. - Try-with-resources captures suppressed exceptions automatically. - In enterprise systems, suppressed exceptions improve debugging of resource issues. Conclusion: Shows suppressed exceptions in try-with-resources.

Quick Links to Explore