What error handling should be used in VB.NET?
Should one use the "On Error Goto ErrorHandler ... Exit Sub ErrHandler ... End Sub
" pattern or should you use the "try { ... } catch { ... } finally { ... }
" pattern?
What error handling should be used in VB.NET?
Should one use the "On Error Goto ErrorHandler ... Exit Sub ErrHandler ... End Sub
" pattern or should you use the "try { ... } catch { ... } finally { ... }
" pattern?
"try { ... } catch { ... } finally { ...}" pattern by a long shot.
C#
try
{
// Do Something that may go wrong
}
catch (Exception ex)
{
//Do something with the error
}
finally
{
//Cleanup
}
or
VB
Try
// Do Something that may go wrong
Catch ex as Exception
//Do something with the error
Finally
//Cleanup
End Try
On Error Goto ErrorHandler ... Exit Sub ErrHandler ... End Sub
is from the VB6 days. Definitely go with Try... Catch... Finally...
A little background
'On Error Goto' is the way things were done in VB 6 before the .Net days. The VB compiler still allows this so you can easily port old VB code to VB.Net. VB.Net is probably the only .Net language that supports this.
'Try Catch Finally' is the .Net way to do things and a lot more flexible allowing you to catch, wrap and rethrow exceptions. It allows for easier interoperation between components written in different languages and is a lot more readable when you do more complex error handling because you don't have goto's.
The most obvious reasons I can think of off the top of my head to steer clear of On Error GoTo...
would have to be:
On Error GoTo
does not discriminate between types of exceptions.On Error GoTo
does not provide as much structure as Try
/Catch
/Finally
(e.g., nesting one Try
/Catch
block within another).On Error GoTo
has no counterpart to Finally
(that I know of).I'm sure in many cases, clever use of On Error GoTo
could mimic the behavior that is built in to VB.NET's Try
/Catch
/Finally
feature. But what would be the point?