Why catch and rethrow an exception in C#?

前端 未结 17 675
遥遥无期
遥遥无期 2020-11-22 14:56

I\'m looking at the article C# - Data Transfer Object on serializable DTOs.

The article includes this piece of code:

public static string Se         


        
17条回答
  •  逝去的感伤
    2020-11-22 15:12

    A valid reason for rethrowing exceptions can be that you want to add information to the exception, or perhaps wrap the original exception in one of your own making:

    public static string SerializeDTO(DTO dto) {
      try {
          XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
          StringWriter sWriter = new StringWriter();
          xmlSer.Serialize(sWriter, dto);
          return sWriter.ToString();
      }
      catch(Exception ex) {
        string message = 
          String.Format("Something went wrong serializing DTO {0}", DTO);
        throw new MyLibraryException(message, ex);
      }
    }
    

提交回复
热议问题