我有一个使用MemoryStream和GZipStream类的API类将字符串压缩并解压缩为字节数组。处理可能引发多个异常的方法的异常
使用这两个类可能会抛出一些异常,我想知道处理抛出的API异常的最佳方法是什么。在这种情况下,使用我自己的Custom Exception来包装每个异常还是更好一些,还是最好在调用代码中捕获每个异常?
我想这是一个问题,不仅限于这个特定的用例,更多的是关于一般异常处理的最佳实践。
/// <summary>
/// Compress the string using the SharpLibZip GZip compression routines
/// </summary>
/// <param name="s">String object to compress</param>
/// <returns>A GZip compressed byte array of the passed in string</returns>
/// <exception cref="Helper.Core.Compression.StringCompressionException">Throw when the compression memory stream fails </exception>
/// <exception cref="System.ArgumentNullException">Throw when string parameter is Null</exception>
/// <exception cref="System.ArgumentException">Throw when the string parameter is empty</exception>
public async Task<byte[]> CompressStringAsync(string s)
{
if (s == null) throw new ArgumentNullException("s");
if (string.IsNullOrWhiteSpace(s)) throw new ArgumentException("s");
byte[] compressed = null;
try
{
using (MemoryStream outStream = new MemoryStream())
{
using (GZipStream tinyStream = new GZipStream(outStream,CompressionMode.Compress))
{
using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
await memStream.CopyToAsync(tinyStream);
}
}
compressed = outStream.ToArray();
}
return compressed;
}
catch (ArgumentNullException ex)
{
throw new StringCompressionException("Argument Was Null", ex);
}
catch (EncoderFallbackException ex)
{
throw new StringCompressionException("Stream Encoding Failure", ex);
}
catch (ArgumentException ex)
{
throw new StringCompressionException("Argument Was Not Valid", ex);
}
catch (ObjectDisposedException ex)
{
throw new StringCompressionException("A Stream Was Disposed", ex);
}
catch (NotSupportedException ex)
{
throw new StringCompressionException("Action Was Not Supported", ex);
}
}
Here是一个很好的发现基地例外。
是不是普遍皱起了眉头赶上基地的异常类?代码分析工具倾向于对此抱怨。 –
@Phil是的,它通常是,因为当你这样做的时候,你也会捕获像'OutOfMemoryException'这样的不可恢复的错误。你应该只捕捉你准备处理的异常。但是在这种情况下,你只是将基础异常封装在一个特定的API中,然后重新投射,所以它可能是好的。除非您执行原始代码的操作,否则您没有其他选择:挑选单个的异常。 .NET中的异常层次结构设计不是很好,我不这么认为。 –