【问题标题】:How can I add exception inside my code?如何在我的代码中添加异常?
【发布时间】:2013-09-02 23:51:59
【问题描述】:

我想检查用户是否在我的 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;
        }
    }

【问题讨论】:

  • 如何检查用户是否输入了无效的登录信息?
  • 异常不应用于控制流。无论如何,SQL 都会为您抛出异常。
  • 你需要捕获异常还是抛出异常?
  • 如果用户登录信息不正确则抛出一个

标签: c# winforms oracle exception


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以将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
            }           
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多