문제

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
}
도움이 되었습니까?

해결책

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

다른 팁

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..
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top