Visual Basic .NET Language Exception handling


Example

During coding, unexpected errors do arise frequently enough, which requires debugging and testing. But sometimes the errors are indeed expected and to bypass it, there is the Try..Catch..Throw..Finally..End Try block.

To manage an error correctly, the code is put into a Try..Catch block, whereby the Catch, as the name states, will catch all the exceptions that arise in this block.

And in case of exception, we have the possibility to Throw the error, that is return it to notify the user or manage it internally in the code itself.

The Finally part is the final code that, whatever the outcome be, if there is an exception or not, the code will run before going out of the block.

In case we need to pop-out of the clock, there is the Exit Try statement that can be used. But here also, the code in the Finally section will be executed before ending.

The syntax is simple;

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

where only the Try and End Try is compulsory. The rest can be ignored but as a good practice, do include the Finally part, even if it would be left blank.

Coming to the exception, there are different type of exception that can be caught. They are ready made exceptions available from the .Net Framework, as below;

Exception ClassBrief Description
System.IO.IOExceptionHandles I/O errors
System.IndexOutOfRangeExceptionRefers to an array index out of range
System.ArrayTypeMismatchExceptionWhen type is mismatched with the array type
System.NullReferenceExceptionHandles errors generated from referencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.
---------------------------------------------------