创建自己的例外

Sta*_*tan 4 .net c# vb.net error-handling

我想建立一些已知错误的建议.假设我有一个Windows表单,需要在对象中设置图像的源路径.肯定是:

  • 一条有效的道路
  • 一个图像
  • 巴布亚新几内亚
  • 尺寸为32 x 32
  • 没有透明度

关于捕获错误的事情是我希望类尽可能地处理错误,而不是Windows窗体.

所以我要说:

Public Class MyImage
    Public Property SourcePath As String
End Class
Run Code Online (Sandbox Code Playgroud)

Sub TestImage()
    Dim imgPath As New MyImage
    Try
        imgPath.SourcePath = "C:\My Documents\image001.png".
    Catch ex As Exception
 MsgBox(ex)
    End Try
End Sub
Run Code Online (Sandbox Code Playgroud)

SourcePath应该是一个指向有效图像文件的字符串路径,即png,即32x32且没有透明度.如果它不是那些中的一个或多个,我只想ex报告那里有什么错误(例如"图像不是32x32"或"图像包含透明度,这不应该."它也不是32x32.).如何为SourcePath上面的属性创建自己的例外?

最重要的是,假设我上面有相同的要求,但不是32x32大小,我需要48x48大小的图像SourcePath.有没有办法为此定制?

Thx提前

Ter*_*lis 9

使用这样的东西:

public class InvalidImageException : Exception
{
    public InvalidImageException() { }
    public InvalidImageException(string message)
        : base(message) { }
    public InvalidImageException(string message, Exception innerException)
        : base(message, innerException) { }
    public InvalidImageException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
    public InvalidImageException(string message, MyImage image)
        : base(message) 
    {
        this.Image = image;
    }
    public MyImage Image { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在设置SourcePath属性时,您可能不应该抛出异常.可能在构造函数中具有该逻辑(接受字符串,sourcepath到构造函数并抛出验证).无论哪种方式,代码看起来都像这样......

public class MyImage
{
    public MyImage(string sourcePath)
    {
        this.SourcePath = sourcePath;
        //This is where you could possibly do the tests. some examples of how you would do them are given below
        //You could move these validations into the SourcePath property, it all depends on the usage of the class
        if(this.height != 32)
            throw new InvalidImageException("Height is not valid", this);
        if(this.Width != 32)
            throw new InvalidImageException("Width is not valid",this);
        //etc etc
    }
    public string SourcePath { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你的代码看起来像这样......

try
{
    imgPath = new MyImage("C:\My Documents\image001.png");
}
catch(InvalidImageException invalidImage)
{
    MsgBox.Show(invalidImage.Message);
}
catch(Exception ex)
{
    //Handle true failures such as file not found, permission denied, invalid format etc
}
Run Code Online (Sandbox Code Playgroud)