Skip to content

Instantly share code, notes, and snippets.

View tech-scripter's full-sized avatar
🎯
Focusing

Vlas Nagibin tech-scripter

🎯
Focusing
View GitHub Profile
@tech-scripter
tech-scripter / SuppressedExceptionExample.java
Last active May 8, 2025 04:03
During a try block, an exception may trigger another while closing resources in finally. In a regular try, the original exception is replaced by the second. With try-with-resources, the second exception is suppressed and added to the original's suppressed exceptions, accessible via Throwable.getSuppressed().
import java.io.Closeable;
import java.io.IOException;
class Resource implements Closeable {
private final String name;
public Resource(String name) {
this.name = name;
}
@tech-scripter
tech-scripter / TryWithResourcesExample.java
Last active May 8, 2025 03:13
Starting with JDK 9, the resource specification in try can also include a variable that was declared and initialized earlier in the program. However, this variable must be effectively final, meaning that after being assigned an initial value, it cannot be reassigned to a new value.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
// The variable is declared and initialized earlier
BufferedReader reader = null;