c# - Assert in code - Asserting in try catch -


i using assert in code verify assumptions , throw give me nice messages, this:

int integerdivide ( int dividend , int divisor ) {      debug.assert ( divisor != 0 );     return ( dividend / divisor );  } 

(exemple assertions in managed code).

now wondering if use check code should not throw exceptions. do:

try {     //code } catch (exceptionthatshouldnthappen ex) {    debug.assert(false,"this exception should never happen!") } 

is done? mean, makes sense code has exceptions caught down line, or break anyway. point, imagine calling code catch wide range of exceptions, aren't meant happen. make sure exceptions break, @ lest in debug, no matter how caller catching them.

i'll go more detailed example: suppose have data access class. can throw sorts of exceptions.

the calling code therefore catch exceptions. (or times?), calling code won't have information enough, or care, exceptions possible. mean, findrecord() fails failed, no matter how. catch , return error page or message, or fallback.

but in data access logic, error should not happen (let's file not found, if file presumed checked before). that's when comes in. assert, no matter how upstream code catching exceptions, break during debug - assertions anyway.

finally, if practice makes sense, i'd know best way it. adding try-catch on place must have big impact (for methods have no try catch @ first). #if debug around try-catch looks ugly hell.

there no need try...catch, exceptions thrown bubble until handles them.

the debug.assert in catch raise exception in debug mode. of time can let debugger break on exceptions.

you should use assertions invariants, , let other exceptions raised until needs handle them.

in case, don't think there want handle exception.

it better have specific argumentexception replace debug.assert, way in release mode exception more useful, in example it's neither here nor there.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -