日期:2014-05-20  浏览次数:20605 次

try catch问题
以下代码运行结果是什么?为什么?
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) {
        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;
            }
        }
    }

但是这样的话是运行不出来结果的,没有可输出的地方。你最好能问一下老师他这个算法是要具体做什么事情。