English 中文(简体)
创建自己的例外
原标题:Creating Own Exceptions

我想要一些关于建立已知错误的建议。假设我有一个Windows窗体,它需要设置对象中图像的源路径。必须是:

  • A valid path
  • An image
  • A PNG
  • 32 x 32 in size
  • No transparency

关于捕获错误的问题是,我希望类尽可能多地处理错误,而不是Windows窗体。

所以我们假设我曾经:

Public Class MyImage
    Public Property SourcePath As String
End Class

Sub TestImage()
    Dim imgPath As New MyImage
    Try
        imgPath.SourcePath = "C:My Documentsimage001.png".
    Catch ex As Exception
 MsgBox(ex)
    End Try
End Sub

SourcePath should be a string path that points to a valid image file, that is a png, that is 32x32 和 has no transparency. If it is not one or more of those, I just want the ex to report back what error(s) are there (like "The image is not 32x32" or "The image contains transparency, which is should not. And it also is not 32x32.). How can I create my own Exceptions for the property SourcePath above?

除此之外,假设我有上面所有相同的要求,但我要求SourcePath上的图像大小为48x48,而不是32x32。有没有办法对此进行自定义?

Thx提前

最佳回答

使用以下内容:

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; }
}

您可能不应该在设置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; }
}

那么你的代码会是这样的。。。

try
{
    imgPath = new MyImage("C:My Documentsimage001.png");
}
catch(InvalidImageException invalidImage)
{
    MsgBox.Show(invalidImage.Message);
}
catch(Exception ex)
{
    //Handle true failures such as file not found, permission denied, invalid format etc
}
问题回答

在SourcePath属性的setter中,您希望进行有效性检查,并根据需要抛出异常。

您可以抛出一个内置的异常类型并向其传递一个字符串以给出特定的错误,也可以创建自己的从System.exception派生的异常类。

你可以选择多种方式来做到这一点,但我可能会做一些大致如下的事情:

void TestImage()
{
    MyImage image = new MyImage();
    try
    {
        image.Load("@C:My Documentsimage001.png");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

其中image.Load()看起来有点像:

void Load(string path)
{
    if (!File.Exists(path))
    {
        throw new FileNotFoundException("File  " + path + "  does not exist.");
    }
    if (/* image is wrong size */)
    {
        throw new InvalidImageSizeException("File " + path + " is not in the correct size - expected 32x32 pixels");
    }
    // etc...
}

有些人会争辩说,你应该有自己的自定义异常类型——如果你愿意,你可以,但我只在标准异常类型没有真正涵盖异常情况时才担心(例如InvalidImageSizeException)。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签