Try Catch

Submitted by: 

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.


[ 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
  9. 'it multiply 3 and "ab"
  10. ans = num1 * num2
  11. MsgBox(ans)
  13. Catch ex As Exception ' catch exception
  15. MsgBox(ex.Message) 'gets the message that decribes the exception
  17. End Try 'end of block

And here’s the output message:


how to import vb project


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.