When to use Try/Catch?

Here’s the rules that I usually follow:

  1. Always use a Try/Catch sequence in a top-level service that is not invoked from a model.
  2. When not in a top-level service, if you are not going to do something useful when you catch the exception, then don’t use a try/catch at all. This is unneeded overhead.
  3. If you do catch an exception and you are not at the top of the call stack, then either handle it gracefully or return a more meaningful message to the caller.
  4. Always do a pub.flow:getLastError as the first statement in your catch block.
  5. Remember that a try/catch sequence in webMethods has the same variable scoping rules as a try / catch in Java (but no compile time checking for scope issues). So, if you need access to a variable in the catch block, make sure that you have defined it before entering the try block. As soon as you enter the catch block, any variables that were defined within the try block will not be available (except via the lastError/pipeline structure - but I typically avoid trying to code against this structure since you don’t really have access to it at design time).
  6. I like to break out exceptions into three “classes”:
  1. Exceptions that you are expecting to occur and can gracefully handle.
  2. Exceptions that you are expecting to occur, but cannot gracefully handle.
  3. Exceptions that you are not expecting to occur.

[/INDENT][INDENT]A bit more on each…
[/INDENT][INDENT]Exceptions that you are expecting to occur and can gracefully handle
[/INDENT][INDENT]In this case, you will take some sort of corrective action in your code (if needed) so that the exception is transparent to the client.

Exceptions that you are expecting to occur, but cannot gracefully handle
In this case, you cannot hide the fact that there is a problem. You will need to agree with the client on either passing back some sort of response code and message or throwing an exception of a particular type. Which method you choose to use will depend largely on the protocol that you are using and the capability / preference of the client. The client may choose to retry the transaction or take other actions on their own.

Exceptions that you are not expecting to occur
In this case, you can do nothing. This will be a fatal condition, however you still need to agree with the client on how the exception will get raised up. However, since the exception is of an unknown type (i.e. it was not preconceived that it might occur), there may be no safe corrective action that either you or the client can take.