すでに、これら 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;
呼び出しと同じ効果がありますか?throw
HandleException
ベストアンサー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; } }