“投掷"和“投掷"有区别吗?和“扔前"?

Is there a difference between quot;throwquot; and quot;throw exquot;?(“投掷和“投掷有区别吗?和“扔前?)
本文介绍了“投掷"和“投掷"有区别吗?和“扔前"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有一些帖子询问这两者之间的区别是什么.
(我为什么还要提这个……)

There are some posts that asks what the difference between those two are already.
(why do I have to even mention this...)

但我的问题有所不同,我在另一个错误上帝般处理方法中调用throw ex".

But my question is different in a way that I am calling "throw ex" in another error god-like handling method.

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.
    }
}

如果 尝试 &在 Main 中使用了 catch,然后我将使用 throw; 重新抛出错误.但是在上面的简化代码中,所有的异常都经过HandleException

If try & catch were used in the Main, then I would use throw; to rethrow the error. But in the above simplied code, all exceptions go through HandleException

throw ex;HandleException 内部调用时是否与调用 throw 效果相同?

Does throw ex; has the same effect as calling throw when called inside HandleException?

推荐答案

是的,有区别;

  • throw ex 重置堆栈跟踪(因此您的错误似乎源自 HandleException)
  • throw 不会 - 原始违规者将被保留.

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

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

这篇关于“投掷"和“投掷"有区别吗?和“扔前"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)