2

MemoryStreamおよびGZipStreamクラスを使用して文字列をバイト配列に圧縮および解凍するAPI クラスがあります。

これら 2 つのクラスを使用すると、多くの例外がスローされる可能性があり、API でスローされた例外を処理する最良の方法は何か疑問に思っていました。この場合、独自のカスタム例外で各例外をラップする方がよいでしょうか、それとも呼び出し元のコードで個々の例外をキャプチャする方がよいでしょうか?

これは、この特定のユース ケースに限定されるものではなく、一般的な例外処理のベスト プラクティスに関する質問だと思います。

/// <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);
    }
}

これは、基本例外のキャッチに関する良い投稿です。

4

3 に答える 3

0

特定の例外を処理し、最後に一般的な例外を処理することを常にお勧めします。また、決定は、特定の例外を受け取ったときに実装する予定のアクションの種類によって異なります。あなたのコードから、すべての特定の例外から同じ例外を発生させているように見えるので、その特定のブロックで実行したい特定のアクションがない限り、基本例外を含む on catch ブロックを使用するか、単にキャッチします。

また、throw new xxxによってスタック トレースがリセットされることにも注意してください。そのため、例外が生成されたという重要な情報を見逃す可能性があります。

于 2013-07-11T10:27:48.063 に答える