Title here
Summary here
Java makes it possible to *recover* from exceptions using try-catch blocks. This mechanism can stop an exception from crashing the program and allow it to continue execution instead.
An example of where this can be useful: a server wouldn't want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients. In fact, this is what Java's `javax.servlet` does by default for HTTP servers.
```java
import java.util.function.Supplier;
public class ExceptionHandling {
// This method throws an exception
public static void mayThrow() {
throw new RuntimeException("a problem");
}
public static void main(String[] args) {
// We use a try-catch block to handle exceptions
try {
// This code is wrapped in a Supplier to mimic Go's defer functionality
Supplier<Void> deferred = () -> {
try {
mayThrow();
} catch (Exception e) {
System.out.println("Recovered. Error:\n " + e.getMessage());
}
return null;
};
// Execute the deferred code
deferred.get();
} catch (Exception e) {
// This catch block won't be executed in this case
System.out.println("This won't be printed");
}
// This code will run, because the exception was caught
System.out.println("After mayThrow()");
}
}
In Java, we use try-catch blocks to handle exceptions. The try
block contains the code that might throw an exception, and the catch
block handles the exception if it occurs.
In this example, we’ve used a Supplier
to mimic Go’s deferred function. The mayThrow()
method is called within this supplier, and any exception it throws is caught and handled.
The catch
block in the main try-catch statement won’t be executed in this case, because the exception is handled within the supplier.
When you run this program, you’ll see:
$ javac ExceptionHandling.java
$ java ExceptionHandling
Recovered. Error:
a problem
After mayThrow()
This demonstrates that the program was able to recover from the exception and continue execution.