我想将一个类中的SqlException Number抛出到另一个类中的常规Exception中.
所以我想要这样的东西(伪代码)
SQL类
catch (SqlException sqlex)
{
if (sqlex.Number == 911)
{
throw new Exception("There is no database to be found");
}
if (sqlex.Number == 1510)
{
throw new Exception("There isn't a database attached");
}
if (sqlex.Number == 5120)
{
throw; //("You do not have permissions to attach this file.");
}
else
{
throw sqlex;
}
}
B级
if (ex == 5120)
{
dostuff();
}
围绕它的“肮脏”方式是我可以用“5120”消息抛出一个新的异常,然后从那里读取它,但我认为这不是最好的方法吗?
谢谢,
最佳答案 通常,可能引发异常的代码在下一层上使用try {} catch {}块包装,并且这与自定义异常相结合.对于可能的多个异常,您可以使用多个catch块:
public class NoPermissionSqlException : Exception
{
public NoPermissionSqlException(string message) : base(message) {}
// ... implement other constructors
}
并使用它:
public void MyMethod() // method that could throw an exception
{
if (sqlex.Number == 5120)
{
throw new NoPermissionSqlException("You do not have permissions to attach this file.");
}
}
并调用代码:
try
{
MyMethod();
}
catch(NoPermissionSqlException ex)
{
// ... handle no permission error here
dostuff();
}
catch(Exception ex)
{
// ... default handler
}