C# で例外をキャッチして再スローするのはなぜですか? 質問する

C# で例外をキャッチして再スローするのはなぜですか? 質問する

私は記事を見ていますC# - データ転送オブジェクトシリアル化可能な DTO について。

この記事には次のコードが含まれています:

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) {
        throw ex;
    }
}

記事の残りの部分は(初心者にとっては)正常かつ合理的に見えますが、try-catch-throw は WtfException をスローします...これは、例外をまったく処理しないこととまったく同じではありませんか?

つまり:

public static string SerializeDTO(DTO dto) {
    XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
    StringWriter sWriter = new StringWriter();
    xmlSer.Serialize(sWriter, dto);
    return sWriter.ToString();
}

それとも、C# のエラー処理に関する基本的なことを見逃しているのでしょうか? Java とほぼ同じ (チェック例外を除く) ですよね? ... つまり、どちらも C++ を改良したものです。

Stack Overflowの質問パラメータなしの catch を再スローすることと何もしないことの違いは何ですか?try-catch-throw は何も実行しないという私の主張を裏付けているようです。


編集:

将来このスレッドを見つけた人のために要約すると...

しないでください

try {
    // Do stuff that might throw an exception
}
catch (Exception e) {
    throw e; // This destroys the strack trace information!
}

スタック トレース情報は、問題の根本原因を特定する上で非常に重要です。

する

try {
    // Do stuff that might throw an exception
}
catch (SqlException e) {
    // Log it
    if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound.
        // Do special cleanup, like maybe closing the "dirty" database connection.
        throw; // This preserves the stack trace
    }
}
catch (IOException e) {
    // Log it
    throw;
}
catch (Exception e) {
    // Log it
    throw new DAOException("Excrement occurred", e); // wrapped & chained exceptions (just like java).
}
finally {
    // Normal clean goes here (like closing open files).
}

より具体的な例外を、より具体的でない例外よりも先にキャッチします (Java と同様)。


参考文献:

ベストアンサー1

まず、記事内のコードが行う方法は悪質です。throw ex例外の呼び出しスタックをリセットし、この throw ステートメントによって、例外が実際に作成された場所に関する情報が失われます。

第二に、単にキャッチしてそのように再スローするだけでは、付加価値は見当たりません。上記のコード例は、throw extry-catch がなくても同様に優れています (または、ビットを考慮すると、さらに優れています)。

ただし、例外をキャッチして再スローしたい場合もあります。ログ記録はその 1 つです。

    try 
    {
        // code that may throw exceptions    
    }
    catch(Exception ex) 
    {
        // add error logging here
        throw;
    }

おすすめ記事