黑马程序员技术交流社区
标题:
在异常中返回对象出错
[打印本页]
作者:
李东城
时间:
2013-2-11 14:53
标题:
在异常中返回对象出错
protected Object get(Class clz,Serializable id){
try{
Object item=getSession().get(clz, id);
return item;
}catch(RuntimeException e){
e.printStackTrace();
}finally{
closeSession();
}
}
复制代码
这段代码为什么提示 必须返回一个Object类型对象。 在try中返回对象有什么需要注意的么?
作者:
刘凯
时间:
2013-2-12 00:07
protected Object get(Class clz,Serializable id){
try{
Object item=getSession().get(clz, id);
return item;
}catch(RuntimeException e){
e.printStackTrace();
}finally{
closeSession();
}
}
这个问题是这个样子的,假如你的Object item=getSession().get(clz, id);发生异常
那就会抛出的异常并被catch(RuntimeException e)截获, 这样一来 return item;就不能被执行,而方法有返回值且为Object 类型的 所以必须有一个返回值
所以 可以这样写
protected Object get(Class clz,Serializable id){
try{
Object item=getSession().get(clz, id);
return item;
}catch(RuntimeException e){
e.printStackTrace();
return null;
}finally{
closeSession();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2