Custom Exception without new throw in .NET -
i not sure if @ possible. (i think should). possible catch customexception without throwing new 1 follows?
try { //some logic throws exception } catch (exception) { throw new customexception(); }
what have follows:
try { //some logic throws exception } catch (customexception) { // handles exception }
i have tried above not catching customexception directly. have "throw new customexception()
" not ideal. doing wrong?
my custom exception class looks follows:
[serializable] public class customexception : exception { public customexception() : base() { } public customexception(string message) : base(message) { } public customexception(string format, params object[] args) : base(string.format(format, args)) { } public customexception(string message, exception innerexception) : base(message, innerexception) { } public customexception(string format, exception innerexception, params object[] args) : base(string.format(format, args), innerexception) { } protected customexception(serializationinfo info, streamingcontext context) : base(info, context) { } }
thanks,
the catch
clause not automatically convert exceptions, not way works. filter exception gets thrown in try
clause. using
catch (customexception e) { }
you handling only customexception
instances or instances of derived exception clasess - in other words catch clause executed if try
block throws of those. so, if instance filenotfoundexception
gets thrown, catch
clause not executed , code result in unhandled filenotfoundexception
.
if intention make code throw customexception
possible exceptions might occur in try
block, need catch of them. general catch block you:
catch (exception e) // catches exceptions of type { throw new customexception(e.message, e); }
note pass original exception in customexception
constructor (message optionally reused, may put own). omitted very important practice, because passing inner exception have complete stack-trace in logs, or better information problem when debugging.
Comments
Post a Comment