Rasim Cekic
Rasim Cekic

Reputation: 67

Can i create a method for exception occurrences?

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();

enter image description here

I can encounter this exception too much. So how can i do this without try..catch?

Upvotes: 1

Views: 68

Answers (3)

Vince
Vince

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

Dmitrii Bychenko
Dmitrii Bychenko

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

Julian
Julian

Reputation: 934

As suggested you need a try catch block for this. You can read about this here

In your example:

try
{
 actuator1.Members["ZamanSetreset"].Active = true;
}
catch(NullReferenceException ex)
{
  //run your method here
}

Upvotes: 1

Related Questions