Reputation: 557
I have never seen this happen in all my years programming and have to ask if anyone else knows why this is....
Excel.Worksheet worksheet;
Excel.Sheets sheets;
Excel.Workbook theWorkbook;
Excel.Application ExcelObj = null;
try
{
ExcelObj = new Excel.Application();
worksheet = new Excel.Worksheet();
string sheetName;
theWorkbook = ExcelObj.Workbooks.Open(txtImportFilePath.Text, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", true, true, 0, true, 1, 0);
sheets = theWorkbook.Worksheets;
}
catch (Exception ex)
{
MessageBox.Show("An error occured: " + ex.InnerException.ToString);
}
finally
{
worksheet = null;
sheets = null;
theWorkbook = null;
ExcelObj.Quit();
ExcelObj = null;
}
The catch block itself is causing the program to crash with an error. The actual error occurs on the line: theWorkbook = ExcelObj.Workbooks.Open(..... The file it's trying to open is corrupted or the extension does not match error.
But when the messagebox tries to show, there is an object reference not set to an instance error.
This is not because of the messagebox. It is because of the ex.InnerException. I tried doing something differet and it threw the error on the ex.InnerException line:
Catch(Exception ex)
{
string err;
err = ex.InnerException; //Object reference not set to an instance.....
}
I have never seen this happen. Any clues or suggestions out there?
Thanks!!!
Upvotes: 1
Views: 1993
Reputation: 32729
it means that there is no inner exception, it is null. if you want to show the message of inner exception if it is present you need to check that first
MessageBox.Show("An error occured: " + (ex.InnerException != null)
? ex.InnerException.ToString()
: ex.ToString());
Inner Exception: When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y. Use the InnerException property to obtain the set of exceptions that led to the current exception.
Upvotes: 0
Reputation: 564891
The problem is that the Exception
you are receiving doesn't have an inner exception.
You should check for this:
catch (Exception ex)
{
if (ex.InnerException != null)
MessageBox.Show("An error occured: " + ex.InnerException.ToString());
else
MessageBox.Show("An error occured: " + ex.ToString());
}
Upvotes: 7