Reputation: 67
I want to use an exception as trigger for the method. How can I do this?
For example when this exception occurs:
actuator1.Members["ZamanSetreset"].Active = true; // <- NullReferenceException here
actuator1.Members["ZamanSetreset"].Connect();
I can encounter this exception too much. So how can i do this without try..catch
?
Upvotes: 1
Views: 68
Reputation: 979
You can use a try catch block
try{
actuator1.Members["ZamanSetreset"].Active = true;
}catch(NullReferenceException ex){
//handle error here
}
EDIT:
alternatively you can do a null check before hand:
if(actuator1 != null && Array.IndexOf(actuator1.Members, "ZamanSetreset") > -1){
actuator1.Members["ZamanSetreset"].Active = true;
}else{
//handle null values
}
Upvotes: 1
Reputation: 186668
Catching NullReferenceException
is at least misleading and at most a dangerous idea. Let's extract a (local) method
bool Perform(string name) {
var actuator = actuator1.Members[name];
if (actuator != null) {
actuator.Active = true;
actuator.Connect();
return true;
}
//TODO: if you want some kind of trigger, put it here
return false;
}
Then use it
Perform("ZamanSetreset");
You can combine these calls:
if (Perform("ZamanSetreset") &&
Perform("Action2") &&
Perform("Action3")) {
// If all actions complete
}
else {
// At least one action is not performed
}
Upvotes: 3