C#自定义异常不可开票或类型无效
我的解决方案中有一个单独的项目,一个库(seclib.dll),用于处理自定义错误消息。 这是全部内容C#自定义异常不可开票或类型无效,c#,exception,C#,Exception,我的解决方案中有一个单独的项目,一个库(seclib.dll),用于处理自定义错误消息。 这是全部内容 using System; using System.IO; namespace seclib { public class Exception : System.Exception { [Serializable] public class FileNotFound : IOException {
using System;
using System.IO;
namespace seclib
{
public class Exception : System.Exception
{
[Serializable]
public class FileNotFound : IOException
{
public FileNotFound() { }
public FileNotFound(string message)
: base(message) { }
public FileNotFound(string message, Exception inner)
: base(message, inner) { }
}
public class ProcessException : ApplicationException
{
public ProcessException() { }
public ProcessException(string message)
: base(message) { }
public ProcessException(string message, Exception inner)
: base(message, inner) { }
}
}
}
当我试图在解决方案的主项目中使用它时(存在引用),如
我有一个错误(在编译之前)“class seclib.Exception.FileNotFound”(或者,第二个捕获中的ProcessException)和“非invocable成员'Exception.FileNotFound不能用作方法”(与下一个捕获相同,即Exception.ProcessException..等)。
如果我删除括号,即将其用作throw seclib.Exception.FileNotFound;等,则我收到的“Exception.FileNotFound”是一个类型,在给定上下文中无效
有人能帮我吗?非常感谢你你需要创建一个新的异常实例来抛出:
// notice the "new" keyword
throw new seclib.Exception.FileNotFound("file error message", e);
异常
正确吗?
为FileNotFound
和ProcessException
定义的构造函数当前将内部Exception
作为参数,但该范围内的Exception
引用封闭的seclib.Exception
类-将构造函数签名更改为:
public FileNotFound(string message, System.Exception inner) // System.Exception will resolve to the type you expect
: base(message, inner) { }
你的
catch
表达式正确吗?
由于FileNotFound
和ProcessException
继承了当前捕获的基本类型,因此可能会多次嵌套,可能需要测试:
try {
}
catch (System.IO.FileNotFoundException e)
{
if(e is seclib.Exception.FileNotFound)
// Already wrapped in our custom exception type, re-throw as is
throw;
throw new seclib.Exception.FileNotFound("file error message", e);
}
或
throw new seclib.Exception.FileNotFound你完全正确,我需要新眼镜和休息。非常感谢。只是一个小小的澄清:我如何使用“e”?它向我抛出一个“无法从System.Exception转换为”seclib.Exception“。我尝试这样做:“throw new seclib.Exception.ProcessException”(“其他一些错误消息,e.InnerException”);“谢谢!@Nick将构造函数签名更改为引用
System.Exception-inner
而不是Exception-inner
(否则将解析为您的自定义父类型)非常感谢,就是这样..非常感谢。
try {
}
catch (System.IO.FileNotFoundException e)
{
if(e is seclib.Exception.FileNotFound)
// Already wrapped in our custom exception type, re-throw as is
throw;
throw new seclib.Exception.FileNotFound("file error message", e);
}
try {
}
catch (seclib.Exception)
{
// already wrapped, move along
throw;
}
catch (System.IO.FileNotFoundException e)
{
throw new seclib.Exception.FileNotFound("file error message", e);
}
catch (System.ApplicationException e)
...