Tutorial :PriorException was unhandled by user code



Question:

I have multiple nested methods with try/catch blocks. If there are any exceptions I want to log the first one and have the flow of control bubble up through the nested methods. I tried to do this by raising a custom exception called PriorException ...

public class PriorException : ApplicationException  {      public PriorException() : base() { }      public PriorException(string message) : base(message) { }  }  

... and writing the catch blocks like so:

try  {      (do stuff here)  }  catch (Exception ex)  {      MyLog.ExceptionError(ex);      if (ex is PriorException) { throw; } else { throw new PriorException(); }  }  

(MyLog ignores PriorException, and the outermost catch block does NOT rethrow.)

However, what is happening is that when an exception is encountered it is caught, logged, and a PriorException is thrown. Then control falls out to the calling method where PriorException is caught and rethrown. But then control moves to the open braces of the else clause of the catch block and the program crashes with "PriorException was unhandled by user code".

I'm still inside one or more nested try/catch blocks which should catch this exception, plus I have AppDomain.CurrentDomain.UnhandledException wired up for good measure. So what's going on?


Solution:1

It sounds like you are debugging. Is the runtime behavior what you expect?

On a side note: I'd highly recommend trying to restructure your code so that you don't have nested try/catch blocks that are being used for program flow. Maintenance could get very tricky as your application progresses.


Solution:2

Since you are doing

try  {      (do stuff here)  }  catch (Exception ex)  {      MyLog.ExceptionError(ex);      if (ex is PriorException) { throw; } else { throw new PriorException(); }  }  

you need to add

catch (PriorException ex)  {    }  

right now your only catching general exceptions.

Edit just realized this is incorrect

Exception does catch the Prior exception.

What is the need to rethrow the exception once its been handled.

You say that the exception is never touch once the exception has been handled and converted to a type of ProperException. Why not just say

catch {MyLog.ExceptionError(ex);}  

and then continue on with your program


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »