Question

How can i handle an exception that occurs when properties in my ViewModel get occurs? The property gets happen before the Loaded event. For example, I have a property (get-only) that calls some data method to return a collection of states to fill a combobox's itemsource. But sometimes SQL will not connect, and I get an exeption. There are multiple properties like this, I want to tell the user that the combos could not be loaded correctly and then just put them back at my home screen. However, i don'twant 5 message boxes if they all fail. Also, why does it continue to try to get the properties, even though i told it to go to the home screen when the first exception occured? Note: the GetStatesList() method also has try/catch and throw in the catch...

try
{
ObservableCollection<string> states=null;
// perform sql query
states=StateDat.Instance.GetStatesList();  //get the collection of state names
}
catch(Exception ex)
{
MessageBox.Show("Error");  //display an error message
MessengerInstance.Send(ViewModelNamesEnum.HomeVM);  //go home
}
Was it helpful?

Solution

Have all the five statements continuously with in 1 try catch, instead of having try catch for each statement, so if exception occurs 2nd statement following 3 will not get executed and at any cost you will have only 1 msg box and you can return to the home screen as well without any issuse

OTHER TIPS

Here is one way you could handle this..

Make separate methods for each property call.. and throw a custom exception to indicate something went wrong with that specific call.. Anyway the outer exception will make sure that if one fails, it bails out..

Method1() {
 try { 
     //Code for Method1 
     }catch(Exception ex) { throw new CustomException(""); }
}

Method2() {
 try { 
     //Code for Method2 
     }catch(Exception ex) { throw new CustomException(""); }
}

Method3() {
 try { 
     //Code for Method3 
     }catch(Exception ex) { throw new CustomException(""); }
}


try {
    Method1();
    Method2();
    Method3();
}catch(CustomException custom) {
 // You would know specific reasons for crashing.. and can return meaningful message to UI.
 } catch(Exception ex) { 
 //Anything that was un-handled
}


class CustomException : Exception {
 //Implementation here..
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top