首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

一路try,finally的面试题

2012-10-27 
一道try,finally的面试题今天一朋友去面试,带回来一道面试题:?public class TryTest {?/** * @param args

一道try,finally的面试题

今天一朋友去面试,带回来一道面试题:

?

public class TryTest {

?

/**

* @param args

*/

public static void main(String[] args) {

?? ? ? ? ? ?System.out.println(trytest());

}

private static int trytest()

{

try{

return 1;

}

finally{

return 2;

}

}

?

}

程序运行后输出2,请添加一些代码,让程序输出1。


-------------------------以下是我的解决方案请思考后再看------------------------------------?方法1:?public class TryTest {
/** * @param args */public static void main(String[] args) { ??? ? ? ? ? ?System.out.println(trytest());}private static int trytest(){ ?try{?return 1;?}finally{if(true)try {throw new Throwable("cccc");// ?throw ? new ? ArrayIndexOutOfBoundsException();} catch (Throwable e) {// TODO Auto-generated catch block}else?return 2;}}
}方法二:? ? ??public class TryTest {
/** * @param args */public static void main(String[] args) { ??? ? ? ? ? ?System.out.println(trytest());}private static int trytest(){ ?? ? ? ? ? ? ? ? ? ? try{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? try{?return 1;? } finally{return 2;? ? ? ? ?}? ? ? ? ? ? ? ? ? ? ? ? ?}finally{? ? ? ? ? ? ? ? ? ? ? ? ? ?return 1;
? ? ? ? ? ? ? ? ? ? ? ? }?}
}----------------------------------------------------------------这个问题你是怎么解决的?谢谢大家的光顾^_^!!?

?

public static int foo() {try{return 1;} finally {if(false==true)return 2;}}
package com.test;public class TryTest {public static void main(String[] args) { System.out.println(trytest()); } public static int trytest() { try{ return 1; } finally { return 2>>1; } } }
这样写不知道对不对,这个是C程序员出的题package com.test;

public class TryTest {
public static void main(String[] args) {     
    System.out.println(trytest());    
}    
   
public static int trytest() {     
    try{
        return 1;    
        
    }
    finally {    
        return 2>>1;    
    }    
}    
} 13 楼 天朗java 2011-07-30   我想面试官的意思应该是不改变 这段代码
try{

return 1;

}

finally{

return 2;



}
的基础上让返回值为1,所以我添加了第二种解决方法,希望大家分享更好的解决方法……

热点排行