请教一个关于异常处理的问题

wangxpengx 2009-09-02 04:57:01
需求:往表中插入数据,如果插入成功,返回 1
如果插入失败返回 2

我对插入代码进行了try catch

在try中return 1

在catch中return 2

这样操作失败...

请问该如何操作?
...全文
103 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
woshayawo 2009-09-02
  • 打赏
  • 举报
回复
学习中!
lxxzhy 2009-09-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wangxpengx 的回复:]
代码:
                  int flag;
try {
this.insertObj(patient);
flag = 1;
} catch (Exception e) {
System.out.println(e.toString());
flag = 2;
}
return flag;
有异常后程序就不再运行了 怎样可以满足我的需求?
[/Quote]
有没有debug一下啊? 感觉不可能没有返回,应该是insertObj方法里面死循环了吧?
o2cola 2009-09-02
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wangxpengx 的回复:]
代码:
                  int flag;
try {
this.insertObj(patient);
flag = 1;
} catch (Exception e) {
System.out.println(e.toString());
flag = 2;
}
return flag;
有异常后程序就不再运行了 怎样可以满足我的需求?
[/Quote]

有异常之后,try块中的其他代码就不再运行,直接跳到catch块中,catch块中的代码还是可以运行的,所以这个方法是没有问题的
yanliang_xt 2009-09-02
  • 打赏
  • 举报
回复

public static int insert() {
int flag = 1;
try
{
/**
/* 相关操作
*/
throw new Exception("asdf");
}
catch (Exception e)
{
flag = 2;
}
return flag;


}


yanliang_xt 2009-09-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wangxpengx 的回复:]
只要添加时出现异常,程序就停掉了啊 就什么都不返回了
[/Quote]

你可以在catch里进行返回的。
wangxpengx 2009-09-02
  • 打赏
  • 举报
回复
代码:
int flag;
try {
this.insertObj(patient);
flag = 1;
} catch (Exception e) {
System.out.println(e.toString());
flag = 2;
}
return flag;
有异常后程序就不再运行了 怎样可以满足我的需求?
wangxpengx 2009-09-02
  • 打赏
  • 举报
回复
只要添加时出现异常,程序就停掉了啊 就什么都不返回了
zhizhuo89 2009-09-02
  • 打赏
  • 举报
回复
对,这只一个标志,成功返回1,为假返回2.
好吃的松子 2009-09-02
  • 打赏
  • 举报
回复
定义一个int flag,在需要的位置修改这个flag, 最后在方法最再return flag
yanliang_xt 2009-09-02
  • 打赏
  • 举报
回复

public int executeUpdate(String sql) throws Exception
{
try{
dbConn = getConn() ; //get connection
if( dbConn == null)
return -1;
if( stmt != null ) {
stmt.close() ;
stmt = null ;
}
stmt= dbConn.createStatement(); //get statement
if(stmt == null)
return -2;
stmt.executeUpdate(sql); //execute
return 0;
} catch(Exception e) {
System.out.println( "executeUpdate[ "+ sql + "] fail. " + e.getMessage() );
return -99;
} finally {
try {
if(stmt!=null){
stmt.close();
stmt = null;
}
}catch(Exception e) {
System.out.println( "Err: executeUpdate() close stmt fail. ") ;
return -88;
}
}
}



与这类似,看书看着怎么修改好。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧