Correct way to assign variables before a try/catch/finally using Excel = Microsoft.Office.Interop.Excel

...

Excel.Application app = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;

object[,] data;

try
{
    app = new Excel.Application();
    books = app.Workbooks;
    book = books.Open("C:\...");

    Excel.Worksheet sheet = book.Worksheets[1];
    Excel.Range range = sheet.UsedRange;
    data = range.Value;
}
catch (Exception ex)
{
    throw ex;
    //To Do...
}
finally
{
    book.Close();
    app.Quit();
}

//code that the uses data object from above e.g.
...


In the code above I have to declare the objects app, books and book outside of the try block so that I have access to them in the finally block. However if I do not assign anything to them (i.e. Excel.Application app; instead of Excel.Application app = null;) then the compiler complains about the line app.Quit() saying "Use of unassigned local variable...". So is it correct to assign null to app etc in this case?

Also books doesn't get used in the finally block so is it better to declare it as I have, or should I declare it in the try block?
Two main issue I can see with your code:


app and book can potentially remain null and therefore your finally code has the potential to throw a NullReferenceException. You need to check for null first before calling methods on these objects.
The way you re-throw the exception will destroy its stacktrace. Instead of this:

catch (Exception ex)
{
    throw ex;
    //To Do...
}


you should do this:

catch (Exception ex)
{
    //To Do...
    throw;
}



As to your question where to declare books - it best practice to limit the scope of variables and declare them as close to their use point as possible.



As mentioned in the comments if you want to pass a custom error message via the exception then the best way forward it to create a custom exception which accepts the original exception as a parameter. If you derive from Exception one of the constructors accepts an inner exception parameter. So something along these lines:

public class DocumentProcessingException : Exception
{
    public DocumentProcessingException(string message, Exception innerException) :
            base(message, innerException)
    { }
}