As written in the introduction, deep knowledge of how exceptions work is critical to developing in Java.  At the simplest of levels, here is how exceptions work:

1) An exceptional condition is detected in a block of code.  The code throws an exception:


try
{
    :
    File file = new File(filename);
    if (!file.exists())
    {
        throw new IOException(“File does not exist” + filename);
    }
    parse(file);
    :
}
catch (IOException e)
{
    logger.error(e);
 }

2) Normal program flow is modified – execution does not continue at the same location.

3) If a try {..} catch(..) block is around the code (or around the call to the function) execution will continue where the exception is caught.


try
{
    :
    File file = new File(filename);
    if (!file.exists())
    {
        throw new IOException(“File does not exist” + filename);
    }
    parse(file);
    :
}
catch (IOException e)
{
    logger.error(e);
 }

4) Normally the catching block of code handles the exception elegantly.

try
{
    :
}
catch (IOException e)
{
    logger.error(e);
    // There is a chance we parsed the XML OK last time so restore it
    xmlRoot = lastXmlRoot;
 }

Having caught the exception, the block of code can also decide not to deal with the exception at all, and rethrow it to be caught elsewhere.

    :
}
catch (IOException e)
{
    logger.error(e);
    // There is a chance we previously parsed the XML so restore it
    xmlRoot = lastXmlRoot;
 }
catch (XmlParseException e)
{
    // let the framework deal with it
    throw e;
}

blog comments powered by Disqus