本文介绍了异常处理无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个SQL数据库的搜索代码,当我搜索存在的数据时,它运行得很好,但是如果我搜索不在数据库上的数据,则异常处理不起作用。 我尝试过: i have a search code fro SQL database, when i'm searching for an data which is exist it works perfectly, but if i search for something which is not on the database exception handling is not working.What I have tried://Search from Student table in srsjason database //BY ID// public Student SearchbyID(string sid) { Student SOB = new Student(); try { string sql = "select * from Student where Student_ID = '" + sid + "' "; SqlCommand cmd = new SqlCommand(sql, m_con); m_con.Open(); SqlDataReader dreader = cmd.ExecuteReader(); if (dreader.Read()) { SOB.setStudentID(dreader[0].ToString()); SOB.setTitle(dreader[1].ToString()); SOB.setFulname(dreader[2].ToString()); SOB.setAddress(dreader[3].ToString()); SOB.setContact(Convert.ToInt32(dreader[4].ToString())); //Int SOB.setemail(dreader[5].ToString()); SOB.setDOB(Convert.ToDateTime(dreader[6].ToString())); //DateTime SOB.setUN(dreader[7].ToString()); SOB.setPW(dreader[8].ToString()); } else { SOB.setStudentID(null); } dreader.Close(); } catch (Exception ex) { MessageBox.Show(" No Student Record Found!!"); } finally { m_con.Close(); } return SOB; } 推荐答案 try{.... dreader = cmd.ExecuteReader(); if (dreader.HasRows){ dreader.Read(); ... } else { // no record found. HasRows = false }}catch (SqlException sqlEx){ // do something}catch (Exception ex){...} 这篇关于异常处理无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-26 18:50