0

I'm trying to catch System.Windows.Automation.ElementNotAvailableException but when the exception happens, visual studio still throw it. Why and how do I fix this? I looked up for System.Windows.Automation.ElementNotAvailableException on Exception Settings (Ctrl + Alt + D + E on VS 2015 commnunity) and that type isn't checked.

The try-catch block look like this:

try
{
    appElement = AutomationElement.RootElement.FindFirst(TreeScope.Children, condition);
}
catch(ElementNotAvailableException)
{
    appElement = null;
}
Julian
  • 33,915
  • 22
  • 119
  • 174
Jack
  • 16,276
  • 55
  • 159
  • 284
  • 1
    What happens when you press F5, it should go the catch block and continue normal program execution. – Habib Oct 04 '16 at 18:28
  • why don't you do this instead `catch(ElementNotAvailableException ex){ MessageBox.Show(ex.Message); }` – MethodMan Oct 04 '16 at 18:30
  • Are you sure the Exception is of type ElementNotAvailableException – Pepernoot Oct 04 '16 at 18:31
  • Is the exception of the type ElementNotAvailableException? – Jean-Claude Colette Oct 04 '16 at 18:31
  • I think OP is confused about what try/catch does. Although, you do not have the ElementNotAvailableException checked in Exception settings, your code is still "catching" the exception. This is supposed to happen. – Jay Oct 04 '16 at 18:35
  • The type is really `ElementNotAvailableException`. Maybe I'm confused, I want to program doesn't stop when the exception of this happen, I thought the application would move on on handled exceptions – Jack Oct 04 '16 at 18:39
  • If you want the program to continue execution, you NEED to catch the exception just as you are doing now. Otherwise, the program will encounter an unhandled exception and terminate. Where is the program blowing up? As others mentioned, are you sure an ElementNotAvailable exception is being thrown. If so, then the statement in your catch section should be getting hit. Is this true? – Jay Oct 04 '16 at 18:54
  • This was my question, I did catch the exception but the programm still found an unhandled exception and terminated, at line of code inside the try catch block. I found out it was a VS settings issue – Jack Oct 05 '16 at 16:05

2 Answers2

2

I found out the solution. I went to Tools -> Options -> Debugging -> General -> unchecked "break when cross appDomain or managed/native boundaries (Managed only) option.

And it worked as expected.

Jack
  • 16,276
  • 55
  • 159
  • 284
0

Review this post on exception handling.

How using try catch for exception handling is best practice

Also, consider adding a generic exception catch block after your current catch block. This will catch other errors besides the specific exception error of the current catch block.

catch(Exception ex)
{
  // exception handling and/or display
}
Community
  • 1
  • 1
JohnH
  • 1,920
  • 4
  • 25
  • 32