Private Sub TextFileExample(ByVal filePath As String)' Verify that the file exists.If System.IO.File.Exists(filePath) = False ThenConsole.Write('File Not Found: ' & filePath)Else' Open the text file and display its contents.Dim sr As System.IO.StreamReader =System.IO.File.OpenText(filePath)Console.Write(sr.ReadToEnd)sr.CloseEnd IfEnd SubEnsure that code in Catch blocks can properly report exceptions to users, whether through thread-safe logging or appropriate messages. This reduces the need for catching an exception thrown by the method. The following example checks whether a file exists before trying to open it. Reasons for this include the following.Catching exceptions at runtime creates additional overhead, and is likely to be slower than pre-checking to avoid exceptions.If a Catch block is not handled correctly, the exception might not be reported correctly to users.Exception handling makes a program more complex.You do not always need a Tr圜atch statement to check for a condition that is likely to occur. Considerations when using a Tr圜atch statementUse a Tr圜atch statement only to signal the occurrence of unusual or unanticipated program events. Returns the Exception object that caused the current exception, or it returns Nothing if there is no original Exception. Returns a link to an associated Help file. In the Code Snippets Manager, expand Code Patterns - If, For Each, Try Catch, Property, etc, and then Error Handling (Exceptions). TipThe Tr圜atchFinally statement is available as an IntelliSense code snippet. If you want to use a variable in more than one block, declare the variable outside the structure. If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Tr圜atchFinally block.Local variables from a Try block are not available in a Catch block because they are separate blocks. Control flow can never reach a Catch block that follows either of these variations.The type is Exception, for example: Catch ex As Exception.The statement has no exception variable, for example: CatchWhen a Tr圜atchFinally statement is nested in another Try block, Visual Basic first examines each Catch statement in the innermost Try block. You should ordinarily use one of these variations as the last Catch block in the structure, after catching all the specific exceptions you expect.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |