C#: 08-Exceptions

Exception catching must go from specific to generic

try{code}
catch{Specific}
catch{Generic}

Catching an Exception & Throwing a Message to Calling Method

Called method can catch an exception and 'throw new' message

        public static double AskDouble(string question)
        {
            try
            {
                System.Console.WriteLine(question);
                return double.Parse(Console.ReadLine());
            }
            catch(Exception)
            {
                // throws the error message up to calling methods
                throw new FormatException("Input was not a number");
            }
        }


 

Calling Try/Catch Block can receive the THROWN message

                catch (FormatException msg)
                {
                    Console.WriteLine(msg);
                }

Console

Employee Name:
asd
Employee Score:
b
System.FormatException: Input was not a number
   at Basics.Projects.EmployeeTrackerOO.Util.EmployeeTrackerUtils.AskInt(String
question) in C:\Users\silosix\source\repos\CEssentials2018\Survey\Projects\Emplo
yeeTrackerOO\Util\EmployeeTrackerUtils.cs:line 26
   at Basics.Projects.EmployeeTrackerOO.EmployeeTracker.ProcessEmployeesWithList
() in C:\Users\silosix\source\repos\CEssentials2018\Survey\Projects\EmployeeTrac
kerOO\EmployeeTracker.cs:line 24
Employee Name:


 

msg.Message

catch (FormatException msg)
{
    Console.WriteLine(msg.Message);
}

Console

Employee Name:
asd
Employee Score:
b
Input was not a number
Tags