Try Catch

Visual Basic Programming has an Exception to handle errors and other exceptional events. As a programmer, it is the best way to use a try catch to deal with unhandled exceptions. Especially when your program has disrupted the normal flow of instructions. Syntax:
Try
    [ tryStatements ]
    [ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
    [ catchStatements ]
    [ Exit Try ] ]
[ Catch ... ]
[ Finally
    [ finallyStatements ] ]
End Try
The main purpose of exceptions is to manage errors. Using visual basic, here’s the built in keywords : Try, Catch, Finally and Throw. •Try – a Try block is where an error occurs. And can be a compound statement. It is always followed by one or more Catch Blocks. •Catch – in catch block, this is the place in a program where we put a catching statement to handle the problem. •Finally – this block is used to execute a given set of statements or optional statements that are executed after all other error processing has occurred. •Throw – it throws an exception when a problem shows up. Instructions: Open Visual Basic and create a new project then save it as “trycatch”. On the windows form add a button, then double click it and add the following code:
  1.  Try
  2.     'declare variable as integer
  3.     Dim num1 As Integer = 3     'correct assignment of value
  4.     'incorrect statement because num2 is declared
  5.     'as integer and we assign string value
  6.     Dim num2 As Integer = "ab"  
  7.     Dim ans As Integer
  8.    
  9.     'it multiply 3 and "ab"
  10.     ans = num1 * num2
  11.     MsgBox(ans)
  12.  
  13.    Catch ex As Exception ' catch exception
  14.  
  15.    MsgBox(ex.Message) 'gets the message that decribes the exception
  16.  
  17.   End Try 'end of block
And here’s the output message:

Comments

Add new comment