home *** CD-ROM | disk | FTP | other *** search
-
- Module MainModule
-
- Sub Main()
- ' Run one of the Textxxxx procedures below by uncommenting only one statement
-
- 'TestException()
- 'TestException2()
- 'TestMultipleExitPointFunction()
- 'TestCatchWhen()
- 'TestCatchWhen2()
- 'TestCatchWhen3()
- 'TestCustomException()
- 'TestGetExceptionMethod()
- 'TestInnerException()
- 'TestInnerException2()
- 'TestExceptionOverhead()
- 'TestOverflowExceptionOverhead()
- 'TestOnErrorPerformance()
-
- ' These statements are usuful when running inside Visual Studio.NET
- Console.WriteLine("")
- Console.WriteLine(">>> press Enter to terminate the program <<<")
- Console.ReadLine()
- End Sub
-
- ' this procedure test Exception properties
-
- Sub TestException()
- ' display the ToString property of an exception object
- ' NOTE: you get different results, depending on whether you compile this code
- ' with or without debug information
- Try
- Throw New DivideByZeroException()
- Catch ex As Exception
- Console.WriteLine(ex.ToString)
- ' Uncomment next line to see the stack trace
- ' Console.WriteLine(ex.StackTrace)
- End Try
- End Sub
-
- ' this procedure tests the Finally block
-
- Sub TestException2()
- Dim cdir As String
- Try
- ' Remember the current directory.
- cdir = FileSystem.CurDir()
- ' Change to another directory
- FileSystem.ChDir("c:\docs")
- ' ....
- Catch ex As Exception
- ' Deal here with errors.
- ' ...
- Finally
- ' In all cases, restore the current directory.
- FileSystem.ChDir(cdir)
- End Try
- End Sub
-
- ' this procedure demonstrates using Try blocks for functions with multiple exit points
-
- Function TestMultipleExitPointFunction() As Integer
- Dim x, y, z As Integer
- Try
- ' ...
- If x > 0 Then Return 1
- ' ...
- If y = 0 Then Return 2
- ' ...
- If z > 0 Then Return 3
- ' ...
- Return 4
- Finally
- ' This code runs whatever exit path the code takes.
- ' ...
- Console.Write("This function is returning the value ")
- Console.WriteLine(TestMultipleExitPointFunction)
- End Try
- End Function
-
- Sub TestCatchWhen()
- Dim x, y, z, res As Integer ' All variables are zero
-
- Try
- ' You can see different behaviors by commenting out or changing
- ' the order of the following statements
-
- ' ...
- res = y \ x
- ' ...
- res = x \ y
- ' ...
- res = x \ z
- Catch ex As DivideByZeroException When (x = 0)
- Console.WriteLine("Division error: x is null.")
- Catch ex As DivideByZeroException When (y = 0)
- Console.WriteLine("Division error: y is null.")
- Catch ex As DivideByZeroException
- Console.WriteLine("Division error: no information on variables")
- Catch
- Console.WriteLine("An error has occurred.")
- End Try
- End Sub
-
- ' this procedure shows the When clause used with properties of the exception object
-
- Sub TestCatchWhen2()
- Try
- ' comment out next statement to see the behavior when another file is missing
- FileOpen(1, "c:\myapp.ini", OpenMode.Input)
- FileOpen(2, "c:\xxxxx.dat", OpenMode.Input)
-
- Catch ex As System.IO.FileNotFoundException When InStr(ex.Message, """c:\myapp.ini""") > 0
- ' the ini file is missing.
- Console.WriteLine("Can't initializa: MyApp.Ini file not found")
- Catch ex As System.IO.FileNotFoundException
- ' Another file wasn't found - extract the file name from the Message property.
- Dim filename As String = Split(ex.Message, """")(1)
- Console.WriteLine("The following file is missing: " & filename)
- Debug.WriteLine(ex.message)
- End Try
- End Sub
-
- ' this procedure shows how to use the When clause to track where the error occurred
-
- Sub TestCatchWhen3()
- Dim currentStep As Integer ' You might also use an Enum value.
-
- Try
- ' Initialize the program.
- currentStep = 1
-
- ' comment and uncomment the Throw statements, so that you can simulate
- ' an exception in different places of this procedure
-
- Throw New System.Exception()
-
- ' Open the data file.
- currentStep = 2
- ' ...
- Throw New System.IO.FileNotFoundException()
-
- ' ...
- Throw New System.Exception()
-
- ' Process the file contents.
- currentStep = 3
- ' ...
- Throw New System.Exception()
-
- ' ...and so on ...
-
- Catch ex As Exception When currentStep = 1
- Console.WriteLine("An error occurred in the initialization step.")
-
- Catch ex As System.IO.FileNotFoundException When currentStep = 2
- Console.WriteLine("The data file wasn't found.")
-
- Catch ex As Exception When currentStep = 2
- Console.WriteLine("An error occurred while opening the data file.")
-
- Catch ex As Exception When currentStep = 3
- Console.WriteLine("An error occurred while processing data.")
- ' Add here other Catch blocks
- ' ...
- End Try
- End Sub
-
- ' this procedure tests custom exception objects
-
- Sub TestCustomException()
- Try
- LoadIniFile()
- Catch ex As UnableToLoadIniFileException
- ' Deal with the most specific error here.
- ' Next statement displays custom message "Unable to load..."
- Console.WriteLine(ex.Message)
- Catch ex As Exception
- ' Deal with other errors here.
- End Try
- End Sub
-
- ' The routine that opens the INI file.
- Sub LoadIniFile()
- Try
- ' Try to open the INI file. (cause an error in this demo)
- FileOpen(1, "c:\missingfile.ini", OpenMode.Input)
-
- Catch ex As Exception
- ' Whatever caused the error, throw a more specific exception.
- Throw New UnableToLoadIniFileException()
- End Try
- End Sub
-
- ' test the Err.GetException method
-
- Sub TestGetExceptionMethod()
- Try
- Call OldStyleErrorHandlerProc()
- Catch ex As DivideByZeroException
- Console.WriteLine("A DivideByZeroException has been caught.")
- End Try
- End Sub
-
- ' this procedure traps an error using an old-style On Error Goto
- ' and return it to the caller as an exception
-
- Sub OldStyleErrorHandlerProc()
- On Error GoTo ErrorHandler
-
- ' cause a division by zero error
- Dim x, y As Integer
- y = 1 \ x
-
- Exit Sub
-
- ErrorHandler:
- ' add here clean up code as necessary
- ' ...
- ' report it to the caller as an Exception object
- Throw Err.GetException
- End Sub
-
- ' this procedure tests inner exceptions
-
- Sub TestInnerException()
- Dim x, y As Integer
-
- Try
- MathIntensiveProc(x, y)
- Catch ex As ArgumentException
- Console.WriteLine("An argument exception has occurred.")
- ' Print a more detailed message about the actual cause of the error.
- Console.WriteLine(ex.InnerException.Message)
- Catch ex As Exception
- ' Deal with other errors.
- Console.WriteLine(ex.Message)
- End Try
- End Sub
-
- Sub MathIntensiveProc(ByVal x As Integer, ByVal y As Integer)
- Try
- ' Process arguments here.
- ' ...
- ' (cause a division by zero error to test this code)
- x = 1 \ y
- Catch ex As Exception
- ' Map any exception to the ArgumentException object,
- ' but remember the inner (actual) exception object.
- Throw New ArgumentException("Wrong arguments", ex)
- Console.WriteLine(ex.GetBaseException.Message())
- End Try
- End Sub
-
- Sub TestInnerException2()
- Try
- InitializeApplication()
- Catch ex As InitializationFailedException
- ' Deal with the most specific error here.
- ' Next statement displays custom message "Unable to load..."
- Console.WriteLine(ex.Message)
- ' also display a message from the inner exception
- Console.WriteLine("Inner exception: " & ex.InnerException.Message)
- Catch ex As Exception
- ' Deal with other errors here.
- End Try
- End Sub
-
- ' The routine that opens the INI file.
- Sub InitializeApplication()
- Try
- ' Try to open the INI file. (cause an error in this demo)
- FileOpen(1, "c:\missingfile.ini", OpenMode.Input)
-
- Catch ex As Exception
- ' Whatever caused the error, throw a more specific exception.
- Throw New InitializationFailedException(ex)
- End Try
- End Sub
-
- ' this procedure tests exception overheads
-
- Dim rand As New Random() ' random number generator
-
- Sub TestExceptionOverhead()
- ' This is the probability that the called method raises an error
- Const Probability As Double = 0.001
- ' This is the number of repetitions
- Const Repetitions As Integer = 1000000
-
- Dim i As Integer
- Dim startTime As Date
- Dim errorCount As Integer
-
- ' test the method that notifies an error condition by throwing an exception.
- startTime = Now
- errorCount = 0
- For i = 1 To Repetitions
- Try
- CanThrowException(Probability)
- Catch
- errorCount += 1
- End Try
- Next
- Console.WriteLine("Exceptions: {0} secs. ", Now.Subtract(startTime))
-
- ' test the method that notifies an error condition by returning False.
- startTime = Now
- errorCount = 0
- For i = 1 To Repetitions
- If CanReturnFalse(Probability) = False Then
- errorCount += 1
- End If
- Next
- Console.WriteLine("Return value: {0} secs.", Now.Subtract(startTime))
- End Sub
-
- ' this method can throw an exception with a given probability.
- Sub CanThrowException(ByVal probability As Double)
- If rand.NextDouble <= probability Then
- Throw New System.Exception()
- End If
- End Sub
-
- ' This method can signal error condition by returning False
- Function CanReturnFalse(ByVal probability As Double) As Boolean
- If rand.NextDouble < probability Then
- ' this simulates an error.
- Return False
- Else
- ' this means a successful operation
- Return True
- End If
- End Function
-
- ' this procedure benchmarks a simple integer addition.
- ' you should compile this code with and without the Remove integer overflow check option
-
- Sub TestOverflowExceptionOverhead()
- Dim start As Date
- Dim i As Integer
- Dim intVar As Integer
- Dim lngVar As Long
-
- start = Now
- For i = 1 To 1000000000
- intVar = intVar + 1
- Next
- Console.WriteLine("Incrementing an Integer variable: {0} secs.", Now.Subtract(start))
-
- start = Now
- For i = 1 To 1000000000
- lngVar = lngVar + 1
- Next
- Console.WriteLine("Incrementing a Long variable: {0} secs.", Now.Subtract(start))
- End Sub
-
- ' this procedure tests the overhead of On Error vs. Try-Catch
-
- Sub TestOnErrorPerformance()
- Dim start As Date
- Dim i As Integer
- Dim res As Integer
-
- start = Now
- For i = 1 To 10000000
- res = TestOnErrorGotoOverhead()
- Next
- Console.WriteLine("TestOnErrorGotoOverhead: {0} secs.", Now.Subtract(start))
-
- start = Now
- For i = 1 To 10000000
- res = TestOnErrorResumeNextOverhead()
- Next
- Console.WriteLine("TestOnErrorResumeNextOverhead: {0} secs.", Now.Subtract(start))
-
- start = Now
- For i = 1 To 10000000
- res = TestTryCatchOverhead()
- Next
- Console.WriteLine("TestTryCatchOverhead: {0} secs.", Now.Subtract(start))
-
- start = Now
- For i = 1 To 10000000
- res = TestNoErrorTrappingOverhead()
- Next
- Console.WriteLine("TestNoErrorTrappingOverhead: {0} secs.", Now.Subtract(start))
- End Sub
-
- ' auxiliary functions
-
- Function TestOnErrorGotoOverhead() As Integer
- On Error GoTo ErrorHandler
- Dim x As Integer = 123
- x = x * x
- ErrorHandler:
- TestOnErrorGotoOverhead = x \ 10
- End Function
-
- Function TestOnErrorResumeNextOverhead() As Integer
- On Error Resume Next
- Dim x As Integer = 123
- x = x * x
- TestOnErrorResumeNextOverhead = x \ 10
- End Function
-
- Function TestTryCatchOverhead() As Integer
- Dim x As Integer = 123
- Try
- x = x * x
- Finally
- TestTryCatchOverhead = x \ 10
- End Try
- End Function
-
- Function TestNoErrorTrappingOverhead() As Integer
- Dim x As Integer = 123
- x = x * x
- TestNoErrorTrappingOverhead = x \ 10
- End Function
- End Module
-
-
-