异常捕获处理与抛出

Posted zhijianhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异常捕获处理与抛出相关的知识,希望对你有一定的参考价值。

1 public int insert(String user_id,String u_name,String u_pwd,String u_phone,String u_address,String u_sex,String u_birthday) throws Exception{
2         String sql="insert into user(user_id,u_name,u_pwd,u_phone,u_address,u_sex,u_birthday)" +"values("+"‘"+user_id+"‘"+","+"‘"+u_pwd+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_address+"‘"+","+"‘"+u_sex+"‘"+","+"‘"+u_birthday+"‘"+")";
3         st=connection.createStatement();
4         int count=0;
5                 count = st.executeUpdate(sql);
6         return count;
7 }

上面这段代码,发生异常后直接抛出给上一级处理,而上一级又抛出给上一级,最后,导致这个异常没有被处理,所以程序代码没有继续执行下去

 

 

 

此次在做数据库课设中,在插入数据时,特意测试一下插入失败的结果,发现自己代码中  异常处理的一些问题。

如上述代码为改正后的代码,插入失败后,发生异常后catch语句捕获处理,程序可以继续执行。代码如下

public int insert(String user_id,String u_name,String u_pwd,String u_phone,String u_address,String u_sex,String u_birthday){
        String sql="insert into user(user_id,u_name,u_pwd,u_phone,u_address,u_sex,u_birthday)" +"values("+"‘"+user_id+"‘"+","+"‘"+u_pwd+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_address+"‘"+","+"‘"+u_sex+"‘"+","+"‘"+u_birthday+"‘"+")";
        try {
            st=connection.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int count=0;
        try {
            count = st.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return count;
    }

 

以上是关于异常捕获处理与抛出的主要内容,如果未能解决你的问题,请参考以下文章

在 Ruby 中引发异常与抛出异常有啥区别?

返回错误消息与抛出异常

在 boost::thread 线程中使用异常

java中的异常处理---捕获异常或者抛出异常

java中的异常处理---捕获异常或者抛出异常

异常处理——捕获并抛出