2011-11-20 119 views
1

我是写作课。下面是功能之一:C# - 抛出异常类

public string GetAttribute(string attrName) 
{ 

    try 
    { 
     return _config.AppSettings.Settings[attrName].Value; 
    } catch(Exception e) 
    { 
     throw new ArgumentException("Element not exists", attrName); 
     return null; 
    } 
} 

然后,我使用它的主要形式MessageBox.Show(manager.GetAttribute("not_existing_element"));

Visual Studio中抛出的线路异常:throw new ArgumentException("Element not exists", attrName);

,但是,我希望得到一个异常在线MessageBox.Show(manager.GetAttribute("not_existing_element"));

我该怎么做? 上传:对不起,英语不好。

回答

1

您正在滥用异常处理。在你的代码中,如果你得到(例如)NullReferenceException,你会抓住它,然后抛出一个ArgumentException

重写你的方法没有任何异常处理:

public string GetAttribute(string attrName) 
{ 
    return _config.AppSettings.Settings[attrName].Value; 
} 

这样,你是不是重置堆栈跟踪和吞咽原始异常。

在获取调用行上的异常方面 - 您将永远无法在不引发异常的行处发生异常。

+0

不知道我完全同意这一点 - 如果设置不存在,将返回一个空值。这不会导致MessageBox.Show调用的问题吗? – Tim

+0

@Tim - 异常会冒泡。 'MessageBox.Show'不会被执行。如果'attrName'不存在,'_config.AppSettings.Settings [attrName]'将是'null',对'.Value'的调用将导致'NullRefereceException'。 – Oded

+0

好的,现在我明白了(在我睡觉的时候)。谢谢:) – Tim

0

几件事情:

首先,你会得到一个无法访问的代码为您捕捉返回空语句警告,因为罚球将返回之前执行。您可以简单地删除返回null语句。其次,我不确定你在MessageBox这一行获得异常是什么意思,但我认为你的意思是你想在那里捕捉它。在试图捕获中调用MessageBox。

try 
{ 
    MessageBox.Show(manager.GetAttribute("not_existing_element")); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.Message); 
}