Friday, 15 February 2013

c# - Is it safe to hold on to exception objects? -



c# - Is it safe to hold on to exception objects? -

i creating test logger include info exceptions thrown can displayed using gui.

is safe utilize next construct:

public class testlogentry { public system.exception exception { get; private set; } public testlogentry(/*...,*/ system.exception exception = null) { //... exception = exception; } }

or next better?

public class testlogentry { public string stacktrace { get; private set; } public system.type exceptiontype { get; private set; } public string exceptionmessage { get; private set; } public testlogentry(/*...,*/ system.exception exception = null) { //... if (exception != null) { stacktrace = exception.stacktrace; exceptiontype = exception.gettype(); exceptionmessage = exception.message; } } }

whilst first approach more flexible (because can contain additional custom data), here concerns:

holding on exception object prolonged period. using lot of memory if exception objects preventing big objects beingness garbage collected. exception returning wrong values when accessed out of context.

q1. above concerns valid?

q2. exception objects typically reference lot of other data?

your concerns valid: exception objects might hold onto arbitrary other objects. rare in practice. have never seen exception.data property used. have seen exception derived class hold onto big using custom fields: webexception has webresponse property!

so see might keeping live expensive unmanaged resource.

i'd re-create out info , discard exception. remember re-create innerexception.

a different concern might exception mutable type. can throw @ time altering stack trace. i'd capture state reason.

also of import memory usage. exception has fields never used. can save them. also, inlining fields log message object eliminate object header , object reference. little gain maybe worth taking in case of frequent exceptions.

c# .net exception logging

No comments:

Post a Comment