以下代码运行结果是什么?为什么?
class Example{
public static void main(String[] args){
for(int i=0; i<10; ++i){
try{
if(i%3 == 0) throw new Exception("E0");
System.out.println(i);
} catch (Exception inner){
i *= 2;
if(i%3 == 0) throw new Exception("E1");
}finally{
++i;
}
}catch(Exception outer){
i += 3;
}finally{
--i;
}
}
}
}
class Example{
public static void main(String[] args){
for(int i=0; i<10; ++i){
try{
if(i%3 == 0) throw new Exception("E0");
System.out.println(i);
} catch (Exception inner){
i *= 2;
if(i%3 == 0) throw new Exception("E1");
}finally{
++i;
}
}catch(Exception outer){
i += 3;
}finally{
--i;
}
}
}
}
2. try和catch以及finally字句分别属于不同的作用域,try里面的局部变量在catch和finally里都是不可见的楼主最好检查一下上面两个原则和你的代码是不是有冲突
public static void main(String[] args) {
int i=0;
try {
for (i = 0; i < 10; ++i) {
try {
if (i % 3 == 0) throw new Exception("E0");
System.out.println(i);
} catch (Exception inner) {
i *= 2;
if (i % 3 == 0) throw new Exception("E1");
} finally {
++i;
}
}
}catch(Exception outer){
i += 3;
}finally{
--i;
}
}
}但是这样的话是运行不出来结果的,没有可输出的地方。你最好能问一下老师他这个算法是要具体做什么事情。
或者我这么问吧:1.当i=3时,当程序走到if(i%3 == 0) throw new Exception("E0")时,接下来程序会跳转到try里还是直接System.out.println(i)?
2.还是当i=3时,当程序走到if(i%3 == 0) throw new Exception("E1")时,程序接下来是不是会跳转到更内层的catch里?执行完catch(Exception outer){
i += 3;
}finally{
--i;
}
后再返回外层执行外层的finally{
++i;
}?
3.假如说最后就是输出4和5.4我能想到,但5是哪来的?
麻烦你了!