This example shows how to use a Try and Catch block to catch exceptions.
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Dim Top As Double = 5
Dim Bottom As Double = 0
Dim Result As Integer
Result = CType(Top / Bottom, Integer)
Catch Exc As System.OverflowException
MsgBox("Attempt to divide by zero resulted in overflow")
This example requires:
The following code example implements a Try...Catch block that handles Exception, IOException, and all the exceptions that derive from IOException.
' Add code for your I/O task here.
Catch dirNotFound As System.IO.DirectoryNotFoundException
Catch fileNotFound As System.IO.FileNotFoundException
Catch pathTooLong As System.IO.PathTooLongException
Catch ioEx As System.IO.IOException
Catch security As System.Security.SecurityException
Catch ex As Exception
' Dispose of any resources you used or opened in the Try block.
Add the code you want to execute to the Try block.
Use this block of code as a starting point for wrapping a data operation in a Try...Catch statement. This Try...Catch
block is designed to catch and rethrow all exceptions. That may not be
the right choice for your project. For a discussion on
exception-handling options, see Best Practices for Using IntelliSense Code Snippets.
You can reduce the likelihood of exceptions by using Windows Forms controls such as the OpenFileDialog Component (Windows Forms) component and the SaveFileDialog Component (Windows Forms) component controls that limit the user choices to valid file names. The FileInfo.Exists
property can check whether a file exists before you try to open it.
Using these controls and classes is not foolproof, however. The file
system can change between the time the user selects a file and the time
that the code runs. Exception handling will therefore nearly always be
required when with working with files.
15 Million Students Helped!
Sign up to view the full answer