代码之家  ›  专栏  ›  技术社区  ›  Stan

创建自己的异常

  •  4
  • Stan  · 技术社区  · 14 年前

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

    • 有效路径
    • 图像
    • PNG
    • 尺寸32×32
    • 没有透明度

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

    所以假设我有:

    Public Class MyImage
        Public Property SourcePath As String
    End Class
    

    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
    

    SourcePath 应该是指向有效图像文件的字符串路径,即PNG,即32x32,并且没有透明度。如果不是一个或多个,我只想 ex 要报告存在哪些错误(如“图像不是32x32”或“图像包含透明度,但不应包含透明度”)。也不是32x32)。我如何才能为该属性创建自己的异常 源代码 上面?

    除此之外,假设我有上述所有相同的要求,但不是32x32大小,我需要48x48大小的图像 源代码 . 有没有办法为这个定制?

    提前通知

    3 回复  |  直到 8 年前
        1
  •  9
  •   Tats_innit    8 年前

    使用类似的方法:

    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属性时,可能不应引发异常。可能在构造函数中包含该逻辑(接受一个字符串,将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 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
    }
    
        2
  •  2
  •   Andrew Cooper    14 年前

    在sourcepath属性的setter中,要进行有效性检查,并根据需要引发异常。

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

        3
  •  2
  •   Justin    14 年前

    有很多种方法可以选择这样做,但是我可能会按照以下方式做:

    void TestImage()
    {
        MyImage image = new MyImage();
        try
        {
            image.Load("@C:\My Documents\image001.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 )