VB.NET Exception Handling
What is an Exception?
An exception is an unwanted error that occurs during the execution of a program and can be a system exception or application exception. Exceptions are nothing but some abnormal and typically an event or condition that arises during the execution, which may interrupt the normal flow of the program.
An exception can occur due to different reasons, including the following:
When an error occurred during the execution of a program, the exception provides a way to transfer control from one part of the program to another using exception handling to handle the error. VB.NET exception has four built-in keywords such as Try, Catch, Finally, and Throw to handle and move controls from one part of the program to another.
Exception Classes in VB.NET
In VB.net, there are various types of exceptions represented by classes. And these exception classes originate from their parent's class 'System.Exception'.
The following are the two exception classes used primarily in VB.NET.
System.SystemException: It is a base class that includes all predefined exception classes, and some system-generated exception classes that have been generated during a run time such as DivideByZeroException, IndexOutOfRangeException, StackOverflowExpression, and so on.
System.ApplicationException: It is an exception class that throws an exception defined within the application by the programmer or developer. Furthermore, we can say that it is a user-defined exception that inherits from System.ApplicationException class.
Syntax of exception handler block
In the above syntax, the Try/Catch block is always surrounded by a code that can throw an exception. And the code is known as a protected code. Furthermore, we can also use multiple catch statements to catch various types of exceptions in a program, as shown in the syntax.
Example to Exception Handle
Let's create a program to handle an exception using the Try, Catch, and Finally keywords for Dividing a number by zero in VB.NET programming.
Creating User-Defined Exceptions
It allows us to create custom exceptions derived from the ApplicationException class.
Let's create a program to understand the uses of User-Defined Exceptions in VB.NET Exception Handling.
Using Try-Catch Statement
Lets' create a program using the Try-Catch statement in VB.NET to handle the exceptions.
In VB.NET exception handling, we can throw an object exception directly or indirectly derived from the System.Exception class. To throw an object using the throw statement in a catch block, such as:
Let's create a program to throw an object in VB.NET exception.
Next TopicVB.NET File Handling