简体   繁体   English

在代码之前捕获对象抛出的异常...c#

[英]Catching exception thrown by object before code...c#

C# .Net 4.6.1 C# .Net 4.6.1

I am using a 3rd party library.我正在使用第 3 方库。 When iterating through its object, my program blows up because the property i'm accessing from the library has thrown an exception.当迭代它的对象时,我的程序崩溃了,因为我从库中访问的属性引发了异常。

在此处输入图片说明

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谢谢

On the breaking line在突破线上

cNew.SetCellFormula(cOld.CellFormula);

You can put a try catch around it, like so你可以在它周围放一个 try catch ,就像这样

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!)这会将消息写入屏幕(记住在生产中将其取出!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM