用户制作了异常类

时间:2014-05-18 18:23:04

标签: c# .net exception

我必须为.NET项目创建自己的异常类。有人可以帮助我如何在代码中使用它?我只是向MessageBox显示用户没有找到图像。但我不知道该怎么做。希望得到一个好的答案。

class RijException : Exception
{
    public RijException()
        : base() { }

    public RijException(string message)
        : base(message) { }

    public RijException(string format, params object[] args)
        : base(string.Format(format, args)) { }

    public RijException(string message, Exception innerException)
        : base(message, innerException) { }

    public RijException(string format, Exception innerException, params object[] args)
        : base(string.Format(format, args), innerException) { }
}       

现在我想用它:

   try
   {
       afbeeldingPictureBox.BackgroundImage =   
        Image.FromFile(@"..\..\Borden\Stilstaan en parkeren\Parkeren toegelaten.png");  
   }
   catch (FileNotFoundException)
   {
            throw new RijException("Can't find the images");
   }

修改

try
        {
            try
            {
                afbeeldingPictureBox.BackgroundImage = Image.FromFile(@"..\..\Borden\Stilstaan en parkeren\Parkeren toegelaten.png");
            }
            catch (FileNotFoundException)
            {
                throw new RijException("ImageNotFound");
                //MessageBox.Show("Afbeeldingen konden niet worden geladen");
            }
        }
        catch (RijException)
        {
            MessageBox.Show("Not able to load the image...");
        }

2 个答案:

答案 0 :(得分:3)

你的例子可以改进,但在此之前让我们采取一个更有用的例子。

想象一下,您有以下代码:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var processor = new FileProcessor();
            processor.Run();
        }
        catch (RijException exception)
        {
            //what will I get here.
        }
    }
}

使用以下类:

public class FileProcessor
{
    private string _myFileName;

    public void Run()
    {
        try
        {
            var fileLoader = new FileLoader();
            Process(fileLoader.Load(_myFileName));
        }
        catch (FileNotFoundException)
        {
            throw new RijException("Can't find requested file");
        }

    }

    private void Process(object file)
    {
        //some logic

    }
}

public class FileLoader
{
    public object Load(string myFileName)
    {
        //throws FileNotFoundException
    }
}

所以调用堆栈将是这样的:

enter image description here

如果我们修改main方法中的代码来打印堆栈跟踪,您认为我们得到了什么?

try
{
    var processor = new FileProcessor();
    processor.Run();
}
catch (RijException exception)
{
    Console.WriteLine(exception.StackTrace);
}

正确答案是:

enter image description here

请参阅?堆栈跟踪显示FileProcessor中发生的错误,而FileLoader中确实发生了错误。原因就是这段代码:

catch (FileNotFoundException)
{
   throw new RijException("Can't find requested file");
}

当您捕获异常并抛出另一个异常时,您必须始终将原始异常作为内部异常包含在内。否则很难理解最初发生的异常。

catch (FileNotFoundException ex)
{
   throw new RijException("Can't find requested file", ex); //includes inner
}

另一个问题是异常消息:"Can't find requested file"。问你自己。如果您在日志文件中收到该消息,您是否能够找出问题所在?至少提供一些背景信息。

最后你有另一个问题。设计异常的最佳实践表明它们应该能够被序列化。为此,您需要包含序列化构造函数并将异常标记为可序列化:

[Serializable]
public class RijException : Exception
{
    public RijException(string message) : base(message)
    {
    }

    public RijException(string message, Exception inner) : base(message, inner)
    {
    }

    //serialization constructor
    protected RijException(
        SerializationInfo info,
        StreamingContext context) : base(info, context)
    {
    }

最后,我会这样写你的练习:

try
{
    var filename = @"..\..\Borden\Stilstaan en parkeren\Parkeren toegelaten.png";
    try
    {
        afbeeldingPictureBox.BackgroundImage = Image.FromFile(filename);
    }
    catch (FileNotFoundException exception)
    {
        throw new RijException("Failed to load " + filename, exception);
    }
}
catch (RijException)
{
    MessageBox.Show("Not able to load the image...");

    //now you would have all information required
    //to figure out where and why something went wrong.
}

<强>摘要

  1. 始终包含内部异常
  2. 提供有用的上下文信息,以便您可以找出问题所在
  3. 确保可以序列化异常。

答案 1 :(得分:2)

捕获一个你无法做多少的异常通常不是一个好主意。只是抓住FileNotFoundException然后抛出一个基本上传达相同信息的新RijException通常不会。

  

我只是向MessageBox显示用户没有找到图像。但我不知道该怎么做。

重构代码以显示消息框的最直接方法是

catch (FileNotFoundException)
{
    MessageBox.Show("Can't find the images.");
    //Don't do this: throw new RijException("Can't find the images");
}

您真的不希望自定义RijException承担显示MessageBox的责任。