Narrowing, Widening and Error Handling in Vb.Net

 

We have two types of errors in programming, those are called Compile-time  Errors & Run-time Errors. We will get Compile-time errors when program is compiling whereas run-time errors will generate when program is executed.

 

Sometime even though our code not generating compile-time errors, will generate run-time errors. In this type of scenario instead of generating run-time errors, producing the compile-time errors is good option because we can solve the errors while compiling the code itself.

 

Today we discuss how to restrict the run-time errors and how convert run-time errors into compile-time errors. Whenever we are assigning wider data type variable to narrower data type variable we might have chance to get run-time errors even though we don't have compile-time errors. Assigning wider data type variable to narrower data type variable is called narrowing and assigning narrower data type variable to wider data type variable is called widening. In the case of widening we won't get any type errors whereas in the case of narrowing we may get run-time errors.

 

while assigning wider data type variable value to narrower data type variable, we will get run-time errors when wider data type of variable value is not compatible with the narrow data type. For example when you are assigning Int16 data type variable to Int32 variable as shown below, we may get run-time errors as shown below.

 

Dim int32 As Int32 = 99999

Dim int16 As Int16 = int32

 

If you run the above code, we will not get any compile-time errors but will get below run-time errors as shown below.

 

 

             

 

 

To avoid the above run-time errors, use Option Strict On. Option Strict On generates compile-time errors instead of run-time errors in the case narrowing even though value is compatible.

 

Use Option Strict On as shown below which avoids the run-time errors but it won't allows assigning the wider data type variable to narrow data type variable. Whenever we are using Option Strict On, if we assign the wider data type variable to narrow data type of variable it generates the compile time errors.

 

Option Strict On

Dim int32 As Int32 = 99999

Dim int16 As Int16 = int32

 

Use Option Strict On statement when you want strictly restricts the narrowing, assigning upper data type variable to lower data type of variable.