Reading — step 1 of 5
Learn
~1 min readLINQ and Exceptions
VB.Net uses .NET exceptions — same as C#.
Try/Catch/Finally:
Try
Dim n = Integer.Parse(input)
Process(n)
Catch ex As FormatException
Console.WriteLine($"bad number: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"unexpected: {ex.Message}")
Throw ' re-throw
Finally
Cleanup()
End Try
When clause for filtered catches (.NET 4+):
Try
DoWork()
Catch ex As HttpException When ex.StatusCode = 404
HandleNotFound()
Catch ex As HttpException
HandleOtherError(ex)
End Try
The When filters without unwinding the stack — useful for keeping stack traces clean.
Custom exceptions:
Class ValidationException
Inherits Exception
Public Property FieldName As String
Public Sub New(field As String, message As String)
MyBase.New(message)
Me.FieldName = field
End Sub
End Class
Throw New SomeException(...) to raise.
Using block — automatic disposal (like C#'s using):
Using reader As New StreamReader("data.txt")
Dim line = reader.ReadLine()
End Using
The IDisposable.Dispose() is called automatically when the block exits, even on exception.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…