「throw」と「throw ex」には違いがありますか? 質問する

「throw」と「throw ex」には違いがありますか? 質問する

すでに、これら 2 つの違いは何かと尋ねる投稿がいくつかあります。
(なぜこれについて言及する必要があるのでしょうか...)

しかし、私の質問は、別のエラー神のような処理方法で「throw ex」と呼んでいる点で異なります。

public class Program {
    public static void Main(string[] args) {
        try {
            // something
        } catch (Exception ex) {
            HandleException(ex);
        }
    }

    private static void HandleException(Exception ex) {
        if (ex is ThreadAbortException) {
            // ignore then,
            return;
        }
        if (ex is ArgumentOutOfRangeException) { 
            // Log then,
            throw ex;
        }
        if (ex is InvalidOperationException) {
            // Show message then,
            throw ex;
        }
        // and so on.
    }
}

try & catchがで使用されている場合はMain、を使用してthrow;エラーを再スローします。しかし、上記の簡略化されたコードでは、すべての例外がHandleException

内部で呼び出された場合、throw ex;呼び出しと同じ効果がありますか?throwHandleException

ベストアンサー1

はい、違いはあります。

  • throw exスタックトレースをリセットします(そのため、エラーは から発生したように見えますHandleException

  • throwそうでない場合、元の犯罪者は保護されることになります。

     static void Main(string[] args)
     {
         try
         {
             Method2();
         }
         catch (Exception ex)
         {
             Console.Write(ex.StackTrace.ToString());
             Console.ReadKey();
         }
     }
    
     private static void Method2()
     {
         try
         {
             Method1();
         }
         catch (Exception ex)
         {
             //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
             throw ex;
         }
     }
    
     private static void Method1()
     {
         try
         {
             throw new Exception("Inside Method1");
         }
         catch (Exception)
         {
             throw;
         }
     }
    

おすすめ記事