BoundForGlory BoundForGlory - 1 month ago 5
C# Question

Catching exception thrown by object before code...c#

C# .Net 4.6.1

I am using a 3rd party library. When iterating through its object, my program blows up because the property i'm accessing from the library has thrown an exception.

enter image description here

So when my program gets to this line of code, the exception is thrown:

case CellType.Formula:
{
cNew.CellFormula = "IFERROR(FF3 / EY3,\"\")";
cNew.SetCellFormula(cOld.CellFormula); //this is where it blows up
break;
}


When debugging the code, I can see the exception has been thrown. The image above shows this. So, I know something has gone wrong in the library property and what I want to do is capture this error BEFORE hitting the line of code using the property and keep going along with the application.

Is there a way to check an object for exceptions and tell my code to skip over it or do whatever? For example:

if (cOld.CellFormula == Exception){
// do something
}


Thanks

Answer

On the breaking line

cNew.SetCellFormula(cOld.CellFormula);

You can put a try catch around it, like so

try
{
    cNew.SetCellFormula(cOld.CellFormula);
}
catch(Exception e)
{
    MessageBox.Show(e.Message);
}

this will display a message box with the error text in it

If you are running this as a console application replace

MessageBox.Show(e.Message);

With

Console.WriteLine(e.Message);

That will write the message to the screen (remember to take it out in production!)

Comments