[Java] Scenes that cannot be reassigned (substantially final)

Multi-exception handling

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;
        }
    }

Define a lambda expression

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

[Java] Scenes that cannot be reassigned (substantially final)
Java Stream cannot be reused.
Java cannot be installed on Ubuntu 13.04
Note that system properties including JAXBContext cannot be used in Java11
Java code that cannot be used from Kotlin (for in-house study sessions)
Check with Java / Kotlin that files cannot be written in UAC on Windows
[Solution] Java cannot be installed on Windows 10 + ATOK 2017
Why Java String typeclass comparison (==) cannot be used
Kotlin's reified function cannot be called from java.
java final modifier
Please note that Spring Boot + Tomcat 8.5.8 cannot be used!
Tomcat cannot be started due to java version change
Write a class that can be ordered in Java
[Java] It seems that `0 <hoge <10` cannot be written in the conditional expression of the ʻif` statement.