A method is supposed to return an int.  How should it handle exceptions?

AlHal2
AlHal2 used Ask the Experts™
on
I'm using Visual Studio 2017 with C#.
I have a method like this.  It's supposed to convert a string to an integer.  If the string does not meet certain conditions there is an exception.
What's the best way to let whatever called this method know the details of the exception?

        public int GetScore(string s)
        {
            try
            {
                int score = 0;
                int totalScore = 0;
                string individualCard = "";
                bool oneJokerFound = false;
                bool twoJokersFound = false;
                int number;
                if (s == null)
                {
                    return 0;
                }
                else if (s == "")
                {
                    return 0;
                }
                for (int i = 2; i < s.Length; i += 3)
                {
                    if (s.Substring(i, 1) != ",")
                    {
                        throw new Exception("Incorrectly formatted string");
                    }
                }
                s = s.Replace(",", "");
                do
                {

}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Don't wrap the method body in a try / catch. Wrap the call in a try catch:

And don't throw an Exception. If you're going to throw, use a more suitable exception type such as FormatException:

throw new FormatException("Error message goes here");

try {

    var myInt = GetScore(someVar);

} catch (FormatExceptione e) {

    Debug.WriteLine(e.Message);

}

Open in new window

Author

Commented:
The call is also a method.
Are there any guidelines for which methods should have a try and catch and which should not?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
If you don't intend to handle the exception inside the method, then don't catch it. In your code, you're not actually doing anything with the exception, so just throw it. Only have a catch block if you intend to do something about it, otherwise just let it bubble up.

If the call is also a method and you don't intend to deal with it there either, then don't catch it. You only want to handle the exception when you can actually do something about it.

Exceptions will keep bubbling up until they're eventually caught. You may have an unhandled Exception handler, in which case that will catch it but your program will end. If you don't have any Exception handlers up the stack, then your program will crash with an Unhandled Exception errror.

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial