Catch block question

froodley

Active member
Joined
Apr 20, 2010
Messages
26
Programming Experience
1-3
I think I know the answer here... but...

let's say you have a try catch block like this:

VB.NET:
try
...
catch se as SpecialException
...
if blah then throw new Exception("blah found")

catch e as Exception
if e.message = "blah found" then foo
end try

Why doesn't this work? if you nest it...
VB.NET:
try
TRY '#2
...
catch se as SpecialException
...
if blah then throw new Exception("blah found")
END TRY '#2
catch e as Exception
if e.message = "blah found" then foo
end try

...thusly, it works, obviously, but my understanding was that the catch blocks for a given try were nested, so that the outermost would potentially catch any exceptions not caught by the inner ones. I guess I'm just wrong :D

Any insights?
 
Maybe you could just format your code properly so it's easy to read:
VB.NET:
Try
    '...
Catch se As SpecialException
    '...
Catch e As Exception
    '...
End Try
VB.NET:
Try
    Try
        '...
    Catch se As SpecialException
        '...
    End Try
Catch e As Exception
    '...
End Try
I'm really sure what you're asking. First you say:
Why doesn't this work?
then you say:
thusly, it works, obviously
That's a complete contradiction. Please explain FULLY and CLEARLY exactly what you expect to happen and exactly what does happen. Only if we know both those things can we determine what "doesn't work" actually means.
 
Apologies for not formatting.

My point was that the second version works, obviously, because the second try-catch structure is catching the error thrown by the inner one.

The first version doesn't work the same way; the error thrown by the se catch block is uncaught. It was my understanding that the catch blocks for a given try worked so that if an exception was uncaught by the first, the second would be tried, and so on. So I was surprised that the first structure didn't work and there was need for another try-catch to trap it. I guess try-catch blocks are "single-use."

I'm not sure my question goes beyond "huh! Well, why doesn't it do THAT?" :p
 
It's not intended to work that way. Each Catch block only catches exceptions thrown in the corresponding Try block. In your first code snippet, the exception that your code is throwing isn't thrown in a Try block, so there's no corresponding Catch block to catch it. For each Try block, only one Catch block will ever be made use of. If you want to catch multiple exceptions then you need multiple Try blocks and each exception must be thrown within one of the Try blocks to be caught by a Catch block.
 
Back
Top