如何在代码中添加异常
本文关键字:添加 异常 代码 | 更新日期: 2023-09-27 18:29:54
我想检查用户是否在我的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;
}
}
您需要在conn = new OracleConnection("Data Source=" + Source + ";User Id=" + Name + ";Password=" + pass + ";");
行周围添加一个Try-Catch。如果出现错误,请在Catch块中进行处理。
您可以将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
}
}
}