Exceptions are simple to inherit from, so there is no harm in adding extra fields in a new subclassed Exception as a payload, provided the information is only to help identify the problem that occurred.  But the text message in an exception is not intended to be user readable, and should never be used to pass data or give a signal/flag for action to other pieces of code, as in the following real example.  

BAD:

try
{
    // imagine lots of code that accesses database here
}
catch (Exception e)
{
    if (e.getMessage().equals("Cannot insert duplicate key row in object 'ProjectIDCode' with "
      + "unique index 'adx_Projects_ProjectIDCode'.\r\n"
      + "Unexpected error inserting Project.\r\n"
      + "The statement has been terminated."))
    {
        errorText = "This code is already associated with another "
                  + "Project, please select another code.";
        return;
    }
    else
    {
        throw e;
    }
}

The developer of the database function only needs to change one letter of the exception message to stop the check from succeeding.  A better way would be to create a specific DuplicateKeyException type that can be caught explicitly.

Good:

try
{
    // imagine lots of code that accesses database here
}
catch (DuplicateKeyException e)
{
    if (“ProjectIDCode”.equals(e.getRow())
    {
        lblError.Text = "This code is already associated with another "
                      + "Project, please select another code.";
        return;
    }
    else
    {
        throw e;
    }
}
blog comments powered by Disqus