The finally clause is necessary to clean up something other than memory. Examples include an open file or network connection, something you’ve drawn on the screen, or even a switch in the outside world:
// exceptions/Switch.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class Switch {
private boolean state = false;
public boolean read() {
return state;
}
public void on() {
state = true;
System.out.println(this);
}
public void off() {
state = false;
System.out.println(this);
}
@Override
public String toString() {
return state ? "on" : "off";
}
}
// exceptions/OnOffException1.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class OnOffException1 extends Exception {}
// exceptions/OnOffException2.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class OnOffException2 extends Exception {}
// exceptions/OnOffSwitch.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Why use finally?
public class OnOffSwitch {
private static Switch sw = new Switch();
public static void f() throws OnOffException1, OnOffException2 {}
public static void main(String[] args) {
try {
sw.on();
// Code that can throw exceptions...
f();
sw.off();
} catch (OnOffException1 e) {
System.out.println("OnOffException1"); // does not output
sw.off();
} catch (OnOffException2 e) {
System.out.println("OnOffException2"); // does not output
sw.off();
}
}
}
/* Output:
on
off
*/
// exceptions/WithFinally.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Finally Guarantees cleanup
public class WithFinally {
static Switch sw = new Switch();
public static void main(String[] args) {
try {
sw.on();
// Code that can throw exceptions...
OnOffSwitch.f();
} catch (OnOffException1 e) {
System.out.println("OnOffException1"); // does not output
} catch (OnOffException2 e) {
System.out.println("OnOffException2"); // does not output
} finally {
sw.off();
}
}
}
/* Output:
on
off
*/
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/Switch.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/OnOffException1.java
4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/OnOffException2.java
5. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/OnOffSwitch.java
7. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/WithFinally.java