如何在代码中添加异常?

时间:2013-09-02 23:52:00

标签: c# winforms oracle exception

我想检查用户是否在我的winForm中输入了错误的登录信息...那么在哪里可以在我的连接类中添加异常?

class Connection
    {
        public static OracleConnection Connection(string Source, string Name, string pass)
        {
            OracleConnection conn = null;
            if(!string.IsNullOrWhiteSpace(Source) && !string.IsNullOrWhiteSpace(Name) && !string.IsNullOrWhiteSpace(pass))
                {
                    conn = new OracleConnection("Data Source=" + Source + ";User Id=" + Name + ";Password=" + pass + ";");
                    return con;
                }

            return con;
        }
    }

2 个答案:

答案 0 :(得分:0)

您需要在conn = new OracleConnection("Data Source=" + Source + ";User Id=" + Name + ";Password=" + pass + ";");行周围添加Try-Catch。如果出现错误,请在Catch块中处理它。

答案 1 :(得分:0)

您可以将try - catch块添加到Connection()方法中,如下所示。当用户提供无效的用户名或密码时,将抛出ORA-1017异常。

class Connection
{
    public static OracleConnection Connection(string Source, string Name, string pass)
    {
        OracleConnection conn = null;

        try         
        {
          if(!string.IsNullOrWhiteSpace(Source) && !string.IsNullOrWhiteSpace(Name) && !string.IsNullOrWhiteSpace(pass))
             {
                conn = new OracleConnection("Data Source=" + Source + ";User Id=" + Name + ";Password=" + pass + ";");                  
             }              
          return con;
        }
        Catch(Exception exception)
        {
            //ORA-01017: invalid username/password; logon denied
        }           
    }
}