Try with multiple catches


public void doStuff()
{

  try {
    doSomethingThatCouldBreak();
  } catch (InvocationTargetException ite) {
    logger.error("Caught error", ite);
    handleError(ite);
  } catch (IOException ioe) {
    logger.error("Caught error", ioe);
    handleError(ioe);
  } catch (SecurityException se) {
    logger.error("Caught error", se);
    handleError(se);
  }
}

Code like this really suggests that each of these exceptions will be a different scenario for your code. The list of potential exceptions, including RuntimeExceptions, is almost endless. If the way each exception is handled is the same don’t try to be cute picking and choosing your exceptions – catch Exception. If you catch it below the top-level of the application (which is where you normally handle exceptions that have bubbled up), you have typically got 2 things to do – log it, throw it wrapped in a RuntimeException or similar.

If you are writing more code for error handling than for functionality you are probably doing something wrong.

Scala HTTP Server using actors

In this tutorial I will be creating a very basic HTTP Server in Scala. In place of the Threads and ExecutorService I would probably use with core Java I will use the Actor pattern:

A main actor will be responsible for starting the listening server and creating child actors to respond to incoming requests.

The actors communicate by the sending of messages, to start the service I will use a StartListening message. I will implement this in scala as a ‘case class’ which will be an immutable value object to hold the port (to listen on) and the number of child threads to handle incoming clients.

Step 1. A Case class for startup options.

We will use the Actor pattern to create our simple HTTP Server


case class StartListening(port: Int = 8080, numberOfThreads: Int = 1)

The StartListening class demonstrates default parameters with default values – a default port of 8080 and default number of threads of 1.