In the AMPS C# client, exceptions can occur that are not thrown to the user. For example, when an exception occurs in the process of reading subscription data from the AMPS server, the exception occurs on a thread inside of AMPS. Consider the following example:
In this example, we set up a simple subscription to wait for messages on the pokes
topic, whose Pokee
tag begins with our username. When messages arrive, we print a message out to the console, but otherwise our application waits for a key to be pressed.
Inside of the AMPS client, the client creates a new thread of execution that reads data from the server, and invokes message handlers and disconnect handlers when those events occur. When exceptions occur inside this thread, however, there is no caller for them to be thrown to, and by default they are ignored.
In applications where it is important to deal with every issue that occurs in using AMPS, you can set an ExceptionListener
via Client.setExceptionListener()
that receives these otherwise unhandled exceptions. Making the modifications shown in the example below, to our previous example, will allow those exceptions to be caught and handled. In this case we are simply printing those caught exceptions out to the console.
If your application will attempt to recover from an exception thrown on the background processing thread, your application should set a flag and attempt recovery on a different thread than the thread that called the exception listener.
At the point that the AMPS client calls the exception listener, it has handled the exception. Your exception listener must not rethrow the exception (or wrap the exception and throw a different exception type).
In this example we have added a call to client.setExceptionListener()
, registering a simple function that writes the text of the exception out to the console. Even though our application waits for a user to press a key, messages to the console will still be produced, both as incoming poke
messages arrive, and as issues arise inside of AMPS.