我有一個使用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中的異常層次結構設計不是很好,我不這麼認爲。 –