1

I`m writing class. Here is one of functions:

public string GetAttribute(string attrName)
{

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

Then, I am using it in the main form MessageBox.Show(manager.GetAttribute("not_existing_element"));

Visual Studio throws an Exception at line:throw new ArgumentException("Element not exists", attrName);

but, I am want to get an Exception at line MessageBox.Show(manager.GetAttribute("not_existing_element"));

How can I do that? P.S: Sorry for bad English.

2 Answers 2

1

You are misusing exception handling. In your code, if you get (for example) a NullReferenceException, you will catch it and then throw an ArgumentException.

Rewrite your method to not have any exception handling:

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

This way, you are not resetting the stack trace and swallowing the original exception.

In terms of getting an exception on the calling line - you will never be able to get an exception at a line that isn't throwing an exception.

Sign up to request clarification or add additional context in comments.

5 Comments

Not sure I entirely agree with this - if the setting isn't there, a null value will be returned. Wouldn't that cause a problem with the MessageBox.Show call?
@Tim - The exception will bubble up. MessageBox.Show will not get executed. _config.AppSettings.Settings[attrName] will be null if the attrName does not exist, the call to .Value would cause a NullRefereceException.
Ok, now I get it (bit past my bedtime here). Thanks :)
NullReferenceException at return _config.AppSettings.Settings[attrName].Value;, not at MessageBox.Show(manager.GetAttribute("not_existing_element"));
@Anton - did you read my answer to the end? It is not possible to get an exception thrown where it doesn't happen.
0

A couple of things:

First, you'll get an unreachable code warning for the return null statement in your catch, because the throw will execute before the return. You can simply delete the return null statement.

Secondly, I'm not sure what you mean by getting the exception at the MessageBox line, but I think you mean you want to catch it there. Wrap the call to MessageBox in a try-catch.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.