Commit dbfd8999 authored by Bhargavi Ghanta's avatar Bhargavi Ghanta

Task 4 completed: Added exception wrapper utility and example

parent dc5f8171
Valid age entered: 32
\ No newline at end of file
......@@ -3,4 +3,4 @@ class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
}
\ No newline at end of file
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.Supplier;
public class IOExceptionWrapper {
@FunctionalInterface
public interface IOCallable<T> {
T call() throws IOException;
}
public static <T> T wrap(IOCallable<T> action) {
try {
return action.call();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static void wrapRunnable(IORunnable action) {
try {
action.run();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@FunctionalInterface
public interface IORunnable {
void run() throws IOException;
}
}
import java.io.*;
public class LegacyApi {
public static void main(String[] args) {
// Using wrap for a method that returns a result
String result = IOExceptionWrapper.wrap(() -> {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
return reader.readLine();
});
System.out.println("First line: " + result);
// Using wrapRunnable for a method that returns void
IOExceptionWrapper.wrapRunnable(() -> {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, world!");
writer.close();
});
System.out.println("Write successful!");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment