Programming Part 8
Programming Part 8
Name:Chibi Tinodaishe
Phone:0781081816
Email:[email protected]
Address:Mutare
WHAT ARE ERRORS ?
Errors: Unexpected events that disrupt program execution.
Try...Catch Block:
Example:
Module ErrorHandlingExample
Sub Main()
Dim numberString As String = "hello"
Try
Dim number As Integer = Integer.Parse(numberString) ' Might
throw FormatException
Console.WriteLine("Number: {0}", number)
Catch ex As FormatException
Console.WriteLine("Error: Invalid number format.")
' Log the error or perform other actions
Finally
Console.WriteLine("Program execution completed.")
End Try
End Sub
End Module
Explanation
1. Try block attempts to parse the string numberString as an integer.
2. If parsing fails (FormatException is thrown), the Catch block executes.
3. The Catch block displays an error message and you can optionally store
the exception object in ex.
4. The Finally block always prints a message, regardless of errors.
Additional Notes:
Consider using the Throw statement to explicitly throw exceptions
within your code.
VB.NET also supports nested Try...Catch blocks for more complex
error handling scenarios.
Explore built-in error handling mechanisms in libraries you use (e.g.,
file I/O).