Throw exception with custom error message if provided.