Why does this compile with "Is" but not with "IsNot"?

Viewed 321

I'm hacking some old VB code, and I want a function to return early if an exception is caught, but if it's a System.UnauthorizedAccessException the function should continue. Just so I don't get XY'ed, I know this is a strange requirement, but I'm rewriting the code in C#, and I just need to see the result of this. I know there's probably a better way to do it. Here is the original code:

Try
    doSomeStuffWithFiles(files)
Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    Exit Sub
End Try

So I added a couple lines:

Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    If TypeOf ex IsNot System.UnauthorizedAccessException Then
        Exit Sub
    End If
End Try

Now, I'm not an expert in VB, but as far as I can tell this is perfectly valid VB. It also exactly matches the sample code for TypeOf on MSDN. However, this code fails to compile. I get this error:

Error   21  'Is' expected.  C:\FilePath 3114    26  Project
Error   22  'UnauthorizedAccessException' is a type in 'System' and cannot be used as an expression.    C:\FilePath 3114    32  Project

If I change that line to

Catch ex As Exception
    MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
    If TypeOf ex Is System.UnauthorizedAccessException Then
        Exit Sub
    End If
End Try

Then everything compiles and runs fine. (Sans the logic being backwards)

I am using visual studio 2013, and targeting .net framework 2.0.

So what's the reason that IsNot is not valid?

2 Answers
Related