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.
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
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 Class||Brief Description|
|System.IO.IOException||Handles I/O errors|
|System.IndexOutOfRangeException||Refers to an array index out of range|
|System.ArrayTypeMismatchException||When type is mismatched with the array type|
|System.NullReferenceException||Handles errors generated from referencing a null object.|
|System.DivideByZeroException||Handles errors generated from dividing a dividend with zero.|
|System.InvalidCastException||Handles errors generated during typecasting.|
|System.OutOfMemoryException||Handles errors generated from insufficient free memory.|
|System.StackOverflowException||Handles errors generated from stack overflow.|