今天一朋友去面试,带回来一道面试题:
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;
}
}
}
----------------------------------------------------------------------------------------------------
这个问题你是怎么解决的?
谢谢大家的光顾^_^!!