[英]How can I throw an SQL Exception Number in one class to regular exception in another? C#
I want to throw an SqlException
Number from one class into a regular Exception
in another. 我想将一个类中的SqlException
Number抛出到另一个类中的常规Exception
中。
So I want something like this (pseudo code) 所以我想要这样的东西(伪代码)
SQL Class 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;
}
}
Class B B级
if (ex == 5120)
{
dostuff();
}
The 'dirty' way around it is that I could just throw a new Exception
with the message "5120" and then read it from there but I don't think that's the best way? 围绕它的“肮脏”方式是我可以用“5120”消息抛出一个新的Exception
,然后从那里读取它,但我认为这不是最好的方法吗?
Thanks, 谢谢,
Normally, code that could potentially throw an exception is wrapped with try{} catch{}
block on a next layer and this is combined with custom Exceptions. 通常,可能引发异常的代码在下一层上使用try{} catch{}
块包装,并且这与自定义异常相结合。 For possible multiple exceptions you can use multiple catch blocks: 对于可能的多个异常,您可以使用多个catch块:
public class NoPermissionSqlException : Exception
{
public NoPermissionSqlException(string message) : base(message) {}
// ... implement other constructors
}
And use it : 并使用它:
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.");
}
}
And calling code: 并调用代码:
try
{
MyMethod();
}
catch(NoPermissionSqlException ex)
{
// ... handle no permission error here
dostuff();
}
catch(Exception ex)
{
// ... default handler
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.