kopaty4
kopaty4

Reputation: 2296

C# - Throwing exception in class

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.

Upvotes: 1

Views: 1735

Answers (2)

Tim
Tim

Reputation: 28530

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

Upvotes: 0

Oded
Oded

Reputation: 499362

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.

Upvotes: 1

Related Questions