Saturday, May 4, 2013

Error Handling using Try... Catch... in VB.NET

Error Handling in VB.NET

You're eventually going to get an error by using Try...Catch.... VB.NET has a statement called the Try...Catch...Finally statement that is made specifically for error handling. I've devoted this post specifically for Error Handling instead of adding this to the Statements section because this is one of the most important statements that you should learn to use.

Let's go over it


"Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code."
This is how one of these statements would look:

[ tryStatements ]
[ Catch [ exception [ As type ] ] [ When expression ] 
[ catchStatements ] ]
[ Exit Try ]
[ Finally
[ finallyStatements ] ]
End Try

The break down
(Courtesy of MSDN)

  • tryStatements
    • This is optional but it's pointless if you do not include these. This is the code where you think an error will occur. There can be multiple statements within for checking.
  • Catch
    • Optional. Multiple Catch blocks permitted. If an exception occurs while processing the Try block, each Catch statement is examined in textual order to determine if it handles the exception. Exception represents the exception that has been thrown.
  • exception
    • Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the error caught.
  • type
    • Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object.
  • When
    • Optional. A Catch statement with a When clause will only catch exceptions when expression evaluates to True. A When clause is only applied after checking the type of the exception, and expression may refer to the identifier representing the exception.
  • expression
    • Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by error number. Used with When keyword to specify circumstances under which the error is caught.
  • catchStatements
    • Optional. Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement.
  • ExitTry
    • Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the Finally block if present, otherwise with the code immediately following the End Try statement. Not allowed in Finally blocks.
  • Finally
    • Optional. A Finally block is always executed when execution leaves any part of the Try statement.
  • finallyStatements
    • Optional. Statement(s) that are executed after all other error processing has occurred.
  • End Try
    • Terminates the Try...Catch...Finally structure.

No comments:

Post a Comment