Demonstrating a user-defined exception class : Custom Exception « Development « VB.Net Tutorial






Public Class Tester
    Public Shared Sub Main
    
      Try
         Console.WriteLine(SquareRoot(123.123))
         Console.WriteLine(SquareRoot(-123.123))

      Catch formatException As FormatException
         Console.WriteLine(formatException.Message)

      Catch negativeNumberException As _
         NegativeNumberException
         Console.WriteLine(negativeNumberException.Message)
      End Try
    End Sub
   Public Shared Function SquareRoot(ByVal operand As Double) As Double

      If operand < 0 Then
         Throw New NegativeNumberException( _
            "Square root of negative number not permitted")
      End If

      Return Math.Sqrt(operand)
   End Function ' cmdSquareRoot

End Class


Public Class NegativeNumberException
   Inherits ApplicationException

   Public Sub New()
      MyBase.New("Illegal operation for a negative number")
   End Sub ' New

   Public Sub New(ByVal messageValue As String)
      MyBase.New(messageValue)
   End Sub ' New

   Public Sub New(ByVal messageValue As String, _
      ByVal inner As Exception)
      MyBase.New(messageValue, inner)
   End Sub

End Class
11.0960803890383
Square root of negative number not permitted








7.6.Custom Exception
7.6.1.Create Custom Exception class
7.6.2.Create your own Exception class by subclassing System.Exception
7.6.3.Demonstrating a user-defined exception class
7.6.4.Inherits System.ApplicationException