Topic: RuntimeException

  Print this page

1.RuntimeException Copy to clipboard
Posted by: lisycn
Posted on: 2005-08-07 12:18

class Switch {
boolean state = false;
boolean read() { return state; }
void on() { state = true; }
void off() { state = false; }
}
class OnOffException1 extends Exception {}
class OnOffException2 extends Exception {}
public class OnOffSwitch {
static Switch sw = new Switch();
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.err.println("OnOffException1");
sw.off();
} catch(OnOffException2 e) {
System.err.println("OnOffException2");
sw.off();
}
}
///:~
为什么在try内抛出RuntimeException会有可能造成执行错误
而在下列程序中家就不会呢?
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.err.println("OnOffException1");
} catch(OnOffException2 e) {
System.err.println("OnOffException2");
} finally {
sw.off();
}
}
} ///:~

2.Re:RuntimeException [Re: lisycn] Copy to clipboard
Posted by: why
Posted on: 2005-08-07 19:32

What are you talking about?
This code snippet is from Thinking in Java.
I believe it (WithFinally class) is to show how to put cleanup code with finally (vs. putting sw.off() are every possible location).


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923