tags:

views:

288

answers:

6

Hello,

Question from beginner, can't find "is not" operator in C#. For example I have code below which do not work, I need to check is err not from class ThreadAbortException.

    catch (Exception err)
    {

        if (err is not ThreadAbortException)
        {
          }
   }

Regards, Tomas

+16  A: 

In this case, wrap and check the boolean opposite:

if (!(err is ThreadAbortException))
Nick Craver
+1: This is the normal way, but catch blocks have a better way.
Richard
+25  A: 

Just change the catch block to:

catch(ThreadAbortException ex)
{
}
catch(Exception ex)
{
}

so you can handle ThreadAbortExceptions and all others separately.

Lee
This is a better solution to the current situation. +1
Rob Fonseca-Ensor
Whew, that was close. I hate seeing `!(a is B)` anywhere!
ChaosPandion
Looking at the code snippet in the question actually made me confused, it was if I'd forgot how to catch exceptions. This is the correct way indeed.
Finglas
Make sure to put the more general Exception object at the bottom. You should always start with the more precise type and go down with the more general one.
Frank
+1 for solving the hidden question
bendewey
+2  A: 

You should be able to do something like this:

catch (Exception err){
    if (!(err is ThreadAbortException)) {
    //Code
    }
}
Pwninstein
One reason you might want to `catch` separate exception types is that you can use a different `finally` block on each type of exception. Perhaps some exceptions are not recoverable (you clean up your resources in the finally block if these exceptions occur) while others are recoverable (you leave resources intact, and allow the caller to sort it out).
Robert Harvey
+5  A: 

More than likely what you ought to do in this circumstance is:

try
{
   // Do Something
}
catch (ThreadAbortException threadEx)
{
   // Do something specific
}
catch (Exception ex)
{
   // Do something more generic
}

You can have multiple catch blocks for a try. Always make sure to order them such that the most specific is on top, and the most generic (catch (Exception ex)) is last because the lookup order is from top to bottom, so if you put the catch (Exception ex) first, it will always be the only one to run.

Nick
A: 

Lee has the best answer,

just to add you should always catch from the most specific down to the most general, in you case the ThreadAbortException is the most specific so deal with that first.

Pharabus
+1  A: 

Perhaps you are looking for this:

if(err.GetType() != typeof(ThreadAbortException))
{

}

But I will strogly recommend using separate catch statement as suggested by Lee

catch(ThreadAbortException ex) 
{ 
} 
catch(Exception ex) 
{ 
} 
Usman Akram