Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将一个类中的SQL异常号抛出到另一个类中的常规异常?C#_C# - Fatal编程技术网

如何将一个类中的SQL异常号抛出到另一个类中的常规异常?C#

如何将一个类中的SQL异常号抛出到另一个类中的常规异常?C#,c#,C#,我想将一个SqlException编号从一个类抛出到另一个类的常规Exception中 所以我想要这样的东西(伪代码) SQL类 catch (SqlException sqlex) { if (sqlex.Number == 911) { throw new Exception("There is no database to be found"); } if (sqlex.Number == 1510) { throw

我想将一个
SqlException
编号从一个类抛出到另一个类的常规
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
}

@系统发育我怎样才能找到数字?在if语句中?是什么阻止您使用属性
编号创建自定义异常
MyCustomSqlException
?然后抛出此异常,并通过调用基本构造函数,将原始异常添加为
InnerException
,参数为
SqlException
。谢谢@Fabjan,
NoPermissionsSqlException
是否在
SQL类中
B类中
忽略此项-抱歉,刚才看到您将其作为一个单独的类编写。我认为它应该是一个单独的类。假设项目名为MyProject,并且有一个DLL库核心。我会创建一个类似MyProject.Core.Exceptions的文件夹smth,并将我所有的异常文件,如
NoPermissionSqlException.cs
放在那里。好的,我会玩一下这个。我还没有开始考虑用类创建自己的异常,所以这将非常有用。你能给我举一个例子来说明你在课堂上“实现其他构造函数”的意思吗?请看:或者谢谢@Fabjan。行