All along we have been talking about catching exceptions, but you may have been
wondering who is throwing them or how you can throw one yourself. If an
exception occurs during the evaluation of an expression, the language runtime
automatically throws the appropriate exception. If an exception must be thrown
programmatically, you would use the throw statement. Below example of using the throw statement.
Throw Example
Public Class ThrowTest
Public Shared Sub
fn(ByVal
age As Int32)
If age < 0 Then
' throw an argument out of range exception if the age is
' less than
zero.
Throw New ArgumentOutOfRangeException("Age
Cannot Be Negative ")
End If
End Sub
Shared Sub
Main()
Try
fn(-10)
Catch e As Exception
Console.WriteLine([String].Concat(e.StackTrace,
e.Message))
Console.ReadLine()
End Try
End Sub
End Class
In this example we have a function called fn, which takes age as an argument. In
this function we check if the age is a negative value, and if so, throw
ArgumentOutOfRangeException. As you can see, throwing an exception is a fairly
simple task.
Let's modify this example, as shown in next given below example.
Example of Exception
Imports System.Text
Public Class ThrowTest
Public Shared Sub
fn(ByVal
age As Int32)
If age < 0 Then
Throw New ArgumentOutOfRangeException("Age
Can Not Be Negative ")
End If
End Sub
Shared Sub
Main()
Try
Try
fn(-10)
Catch e As Exception
Console.WriteLine([String].Concat(e.StackTrace,
e.Message))
Throw
' or we could also have called throw e ;
End Try
Catch e As Exception
Console.WriteLine("In
the outer catch")
' Executing this statement would cause a
' NullreferenceException
'Console.WriteLine(e.InnerException.Message);
Console.WriteLine([String].Concat(e.StackTrace,
e.Message))
End Try
Console.ReadLine()
End Sub
End Class
In the above example we add a throw statement in the catch block basically rethrowing
System.Exception causing the same exception to occur in the catch clause. So, if
we have one more try block outside the inner try block, the outer try-catch
block catches the exception.
One last thing about the throw statement: you will never need to throw system
exceptions such as IndexOutOfRange or NullReferenceException, which are thrown
normally by the runtime. The .NET framework developer specification requires
that you don't throw these exceptions programmatically. However, if you really
wanted to do it, you could write a piece of code that throws these exceptions
programmatically and compiles and executes successfully.
Conclusion
Hope this article would have helped you in understanding Throw Statement in
VB.NET