RSinohara
RSinohara

Reputation: 732

Assert in code - Asserting in try catch

I am using assert in code to verify assumptions and throw give me nice messages, like this:

int IntegerDivide ( int dividend , int divisor )
{ 
    Debug.Assert ( divisor != 0 );
    return ( dividend / divisor ); 
}

(exemple from Assertions in Managed Code).

Now I am just wondering if I could use that to check for code that should not throw exceptions. Something like this could do:

try
{
    //code
}
catch (exceptionThatShouldntHappen ex)
{
   Debug.Assert(false,"This exception should never happen!")
}

Is that done? I mean, obviously it only makes sense for code that has its exceptions caught down the line, or it would break anyway. But that is the point, you imagine the calling code will catch a wide range of exceptions, but some just aren't meant to happen. You make sure that those exceptions always break, at lest in debug, no matter how the caller is catching them.

I'll go for a more detailed example: suppose I have a data access class. It can throw all sorts of exceptions.

The calling code will therefore catch exceptions. Sometimes (or most times?), the calling code won't have information enough, or care, what exceptions are possible. I mean, a FindRecord() that fails failed, no matter how. You catch and return an error page or a message, or even fallback.

But in the data access logic, some error should not happen (let's say file not found, if the file is presumed to be checked before). That's when this comes in. You assert, so that no matter how the upstream code is catching exceptions, it will break during debug - which is what assertions are for anyway.

Finally, if this practice makes sense, I'd like to know what is the best way to do it. Adding try-catch all over the place must have a big impact (for methods that have no try catch at first). #if DEBUG around the try-catch looks ugly as hell.

Upvotes: 1

Views: 909

Answers (1)

DaveShaw
DaveShaw

Reputation: 52788

There is no need to do the try...catch, any exceptions that are thrown will bubble up until someone handles them.

The Debug.Assert in the catch would just raise an exception only in debug mode. Most of the time the you can just let the debugger break on exceptions.

You should use Assertions for invariants, and just let other exceptions be raised until something needs to handle them.

In your case, I don't think there is anything you would want to handle the exception.

It could be better to have a specific ArgumentException replace the Debug.Assert, that way in release mode the exception is more useful, but in your example it's neither here nor there.

Upvotes: 1

Related Questions