开发者

PriorException was unhandled by user code

开发者 https://www.devze.com 2023-01-04 21:12 出处:网络
I have multiple nested method开发者_如何学编程s 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

I have multiple nested method开发者_如何学编程s 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消