"Exception Error Trapping" Please respond to the following:

User Generated


Computer Science

Question Description

Write a Visual Basic snippet example to trap an error. Consider: running out of disk space, database failure, and hard drive failures.

Student has agreed that all tutoring, explanations, and answers provided by the tutor will be used to help in the learning process and in accordance with Studypool's honor code & terms of service.

Explanation & Answer


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")
End Try

This example requires:

  • A reference to the System namespace.

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
    Throw dirNotFound
Catch fileNotFound As System.IO.FileNotFoundException
    Throw fileNotFound
Catch pathTooLong As System.IO.PathTooLongException
    Throw pathTooLong
Catch ioEx As System.IO.IOException
    Throw ioEx
Catch security As System.Security.SecurityException
    Throw security
Catch ex As Exception
    Throw ex
    ' Dispose of any resources you used or opened in the Try block.  
End Try

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.


wnxbobqb (32)
Boston College

Excellent resource! Really helped me get the gist of things.