e is effectively final.
public static void main(String[] args) throws IOException{
try{
throw new IOException();
}catch (RuntimeException | IOException e){
e = new RuntimeException(); // Cannot assign a value to final variable 'e'
throw e;
}
}
However, when catching a single exception instead of multi, it is possible to reassign the caught exception and its subclasses.
static class FooException extends Exception{}
static class BarException extends FooException{}
public static void main(String[] args) throws FooException{
try{
throw new FooException();
}catch (FooException fe){
fe = new FooException();
fe = new BarException();
throw fe;
}
}
In the example below, the local variable used in the lambda expression is effectively final and a compile error occurs when reassigning.
public interface Greeting {
void sayHi(String name);
}
String name = "Ken";
Greeting g = n -> System.out.println("Hi, " + name);
name = "Taro"; //★ Compile error here
g.sayHi(name);
try-with-resources
JDBC example that is not practically final but cannot be reassigned
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection connection = null;
try (connection = DriverManager.getConnection("url") { // unknown class "connection"
} catch (SQLException e) {
e.printStackTrace();
}
By the way, it is possible with a normal try-catch
try {
connection = DriverManager.getConnection("url");
} catch (SQLException e) {
e.printStackTrace();
}
Recommended Posts