How to catch rule exception

I had a rule which crashed because of an not existing command to an item. This exception causes the rule to not run to the end.

Is there a way to prevent this, so that the rules runs to the end


rule "PresistenceWiederherstellen"
Item SW_PresistenceWiederherstellen changed to ON
gRestoreState.members.forEach[item |



This rule crashed on contacts, because contacts cannot handle sendCommand (my fault as a programmer). But this causes the rule to stop and not do SW_PresistenceWiederherstellen.postUpdate(OFF).

Any idea to solve this? and let the rule continue with next line.

It would be a good idea to test the type of each Item before sending a command to it.

 if (item instanceof SwitchItem)  { ......

EDIT - an afterthought, if you are restoring states from persistence, would not want to use postUpdate rather than command?

thanks for the answer,

but my question was more generic. Is there a way to let the script run to the end, even if there is an exception?

The provided example is only an example to clarify, which I solved by myself.

I don’t think so. If it is broken, you have to fix it.
In many cases it would make no sense to continue operations with possible “faulty” variables etc. That would be harder for us to detect, let alone fix.

I think you are right. But this causes a monitoring of rules on runtime to detect exceptions in rule.

I will implement such monitoring through the logfile.

This will be the best way, alert if exception occurs and then look how to fix it.


You have to add try/catch/finally to your rules or add error checking to prevent the exception from being thrown in the first place.

The entire purpose of exceptions is to stop everything and back out of the programming stack until you find a catch that handles that exception. The only way to prevent that is to prevent the exception in the first place or provide your own catch.

   try {
      // do some stuff
   catch(Throwable t) {
      logError("Error", "Some bad stuff happened in my rule: " + T.toString)
   finally {
      // always runs even if there was an error, good place for cleanup