Performance Considerations for throwing Exceptions

前端 未结 8 1117
旧时难觅i
旧时难觅i 2020-12-19 03:17

I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:

try
{
    ... // s         


        
8条回答
  •  眼角桃花
    2020-12-19 04:13

    As others have stated, the best performance comes from the bottom one since you are just rethrowing an existing object. The middle one is least correct because it looses the stack.

    I personally use custom exceptions if I want to decouple certain dependencies in code. For example, I have a method that loads data from an XML file. This can go wrong in many different ways.

    It could fail to read from the disk (FileIOException), the user could try to access it from somewhere where they are not allowed (SecurityException), the file could be corrupt (XmlParseException), data could be in the wrong format (DeserialisationException).

    In this case, so its easier for the calling class to make sense of all this, all these exceptions rethrow a single custom exception (FileOperationException) so that means the caller does not need references to System.IO or System.Xml, but can still access what error occurred through an enum and any important information.

    As stated, don't try to micro-optimize something like this, the act of throwing an exception at all is the slowest thing that occurs here. The best improvement to make is to try avoiding an exception at all.

    public bool Load(string filepath)
    {
      if (File.Exists(filepath)) //Avoid throwing by checking state
      {
        //Wrap anyways in case something changes between check and operation
        try { .... }
        catch (IOException ioFault) { .... }
        catch (OtherException otherFault) { .... }
        return true; //Inform caller of success
      }
      else { return false; } //Inform caller of failure due to state
    }
    

提交回复
热议问题