handle exceptions

  • Thread starter Thread starter Boni
  • Start date Start date
B

Boni

Dear all,

is it possible to handle 2 exception tipes in one block?

I.e

Try

if XXX then

throw new TypeA

else

throw new TypeB

end if

Catch x As TypeA

Doa

End Try

Catch x As TypeB

DoB

End Try
 
Boni said:
is it possible to handle 2 exception tipes in one block?

You can use a generic exception type such as 'Exception' or
'ApplicationException' as type name in 'Catch ex As <TypeName>'. This
solution can be combined with a 'TypeOf' check inside the 'When' part of the
'Catch' statement:

\\\
Try
...
Catch ex As Exception _
Where _
TypeOf ex Is OverlowException OrElse _
TypeOf ex Is BadImageFormatException
...
Catch ex As Exception
...
End Try
///
 
Since you're defining the types of exceptions you can also do it in the
following way

Try
if XXX then
throw new TypeA
else
throw new TypeB
end if
Catch xA As TypeA
Doa
Catch xB As TypeB
DoB
End Try

Note that I removed the End Try you have in between the catches. Also
note that each catch has to have a different variable name, but that
shouldn't be an issue.
Catching multiple types of exceptions is extremely helpful when having
to handle specific types of exceptions. I particularly use it a lot
when I'm doing HTTP/HTTPS communications such as...
Try
'Do whatever code I need here to post to a website
Catch webEx as WebException
'Handle the web exception, knowing that it's an exception that
deals particularly with web based code.
Catch ex as Exception
'Handle all other types of exceptions, since every type of .NET
exception inherits from the generic Exception.
End Try
 
is it possible to handle 2 exception tipes in one block?

Yes; catch a more "generic" Exception Type, then interrogate the
Exception you've caught to find out what it actually is.

.. . .
Catch ex as Exception
If TypeOf ex Is ArgumentException Then
. . .
End If

Note that you /can/ go down the road of defining your own,
custom Exceptions and inherit one from the other, something like :

Class myBasicException
Inherits ApplicationException
. . .
End Class

Class myNumberedException
Inherits myBasicException
. . .
Public Number as Integer
. . .
End Class

Class myOtherException
Inherits myBasicException
. . .
End Class

then

.. . .
Catch ex as myBasicException
If Typeof ex Is myNumberedException Then
ElseIf Typeof ex Is myOtherException Then
Else
Throw
End If
Catch ex as ApplicationException
. . .
Catch ex as Exception
. . .

HTH,
Phill W.
 
Back
Top