You can create a custom exception and throw them during the execution of your function. As a general practice you should only throw an exception when your function could not achieve its defined functionality.
Generally most of the exceptions are not that critical, but there are some really serious exceptions that you might not be capable to handle, such as the famous System.StackOverflowException. However, there are others that might get hidden by Catch ex As Exception, such as System.OutOfMemoryException, System.BadImageFormatException and System.InvalidProgramException. It is a good programming practice to leave these out if you cannot correctly handle them. To filter out these exceptions, we need a helper method:
The Un-catchable Exception
Although Catch ex As Exception claims that it can handle all exceptions - there are one exception (no pun intended).
Oops... There is an un-caught System.StackOverflowException while the console didn't even print out anything! According to MSDN,
Starting with the .NET Framework 2.0, you can’t catch a
StackOverflowException object with a try/catch block, and the
corresponding process is terminated by default. Consequently, you
should write your code to detect and prevent a stack overflow.
So, System.StackOverflowException is un-catchable. Beware of that!
Try Catch in Database Operation
You can use Try..Catch to rollback database operation by placing the rollback statement at the Catch Segment.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0