VB.Net Tutorial/Development/Exception

Материал из VB Эксперт
Перейти к: навигация, поиск

Basics of Visual Basic exception handling

<source lang="vbnet">Public Class Tester

   Public Shared Sub Main
   
     Try
        Dim numerator As Integer = Convert.ToInt32("123")
        Dim denominator As Integer = Convert.ToInt32("321")
        Dim result As Integer = numerator \ denominator
        Console.WriteLine(result)
     Catch formattingException As FormatException
        Console.WriteLine("You must enter two integers")
     Catch dividingException As DivideByZeroException
        Console.WriteLine(dividingException.Message)
     End Try
   End Sub

End Class</source>

0

Catch Exception in a function

<source lang="vbnet">Module Module1

   Sub Main()
           Try
               AddNumbers(1, 2)
           Catch Except As Exception
               Console.WriteLine("Call generated error: " & Except.Message)
           End Try
   End Sub
   Function AddNumbers(ByVal A As Integer, ByVal B As Integer) As Integer
       Try
           Throw New ArithmeticException()
       Catch Except As Exception
           Console.WriteLine(Except.Message)
       End Try
   End Function

End Module</source>

Overflow or underflow in the arithmetic operation.

Convert Exception to String

<source lang="vbnet">Module Module1

   Sub Main()
       Dim A, B, C As Integer
       A = 3
       B = 0
       Try
           C = A Mod B
       Catch Except As Exception
           Console.WriteLine(Except.ToString())
       End Try
   End Sub

End Module</source>

System.DivideByZeroException: Attempted to divide by zero.
   at Module1.Main()

Display Exception Trace

<source lang="vbnet">Module Module1

   Sub Main()
       Try
           Console.WriteLine("Result: ", First())
       Catch Except As Exception
           Console.WriteLine(Except.StackTrace)
       End Try
   End Sub
   Private Function First() As Integer
       First = Second()
   End Function
   Private Function Second() As Integer
       Second = Third()
   End Function
   Private Function Third() As Integer
       Dim A As Integer = 0
       Third = 100 Mod A
   End Function

End Module</source>

at Module1.Main()

Exception fields

<source lang="vbnet">Imports System.IO Module Module1

   Sub Main()
       Dim SourceFile As StreamReader
       Try
           SourceFile = New StreamReader("FilenameISBad.XXX")
       Catch Except As Exception
           Console.WriteLine(Except.Message)
           Console.WriteLine(Except.Source)
           Console.WriteLine(Except.StackTrace)
           Console.WriteLine(Except.TargetSite.Name)
       End Try
   End Sub

End Module</source>

Get Message from Exception

<source lang="vbnet">Module Module1

   Sub Main()
       Dim A, B, C As Integer
       A = 3
       B = 0
       Try
           C = A Mod B
       Catch Except As Exception
           Console.WriteLine(Except.Message())
       End Try
   End Sub

End Module</source>

Attempted to divide by zero.

Serializable Exception Inheriting NullReferenceException

<source lang="vbnet">Imports System Imports System.Runtime.Serialization

   <Serializable()> Public Class NodeNotFoundException : Inherits NullReferenceException
       Dim st As String()
       "Constructors
       Public Sub New()
           MyBase.New("No such node found in your collection.")
       End Sub
       Public Sub New(ByVal message As String)
           MyBase.New(message)
       End Sub
       Public Sub New(ByVal message As String, ByVal inner As Exception)
           MyBase.New(message, inner)
       End Sub
   End Class</source>

Set Exception HelpLink

<source lang="vbnet">Option Strict On

Imports System
Class Tester
    Public Shared Function DoDivide(ByVal a As Double, ByVal b As Double) As Double
        If b = 0 Then
            Dim e As New System.DivideByZeroException( )
         e.HelpLink = "http://www.vbex.ru"
            Throw e
        End If
        If a = 0 Then
            Throw New System.ArithmeticException( )
        End If
        Return a / b
    End Function "DoDivide
    Shared Sub Main( )
        Try
            Dim a As Double = 5
            Dim b As Double = 0
            Console.WriteLine("{0} / {1} = {2}", a, b, DoDivide(a, b))
        Catch e As System.DivideByZeroException
            Console.WriteLine("DivideByZeroException! Msg: {0}", e.Message)
            Console.WriteLine("Helplink: {0}", e.HelpLink)
            Console.WriteLine("Stack trace: {0}", e.StackTrace)
        Catch
            Console.WriteLine("Unknown exception caught!")
        Finally
            Console.WriteLine("Close file here.")
        End Try
    End Sub "Main
End Class "Tester</source>
DivideByZeroException! Msg: Attempted to divide by zero.
Helplink: http://www.vbex.ru
Stack trace:    at Tester.DoDivide(Double a, Double b)
   at Tester.Main()
Close file here.

Throw Exception out of a Method

<source lang="vbnet">Option Strict On

Imports System
Class Tester
    Shared Sub Main( )
        Console.WriteLine("Enter Main...")
        Console.WriteLine("Enter Run...")
        Func1( )
        Console.WriteLine("Exit Run...")
        Console.WriteLine("Exit Main...")
    End Sub
    Public Shared Sub Func1( )
        Console.WriteLine("Enter Func1...")
        Func2( )
        Console.WriteLine("Exit Func1...")
    End Sub
    
    Public Shared Sub Func2( )
        Console.WriteLine("Enter Func2...")
        Throw New System.Exception( )
        Console.WriteLine("Exit Func2...")
    End Sub
End Class</source>
Enter Main...
Enter Run...
Enter Func1...
Enter Func2...
Unhandled Exception: System.Exception: Exception of type "System.Exception" was thrown.
   at Tester.Func2()
   at Tester.Main()

Use properties Message, StackTrace and InnerException

<source lang="vbnet">Class Tester

  Shared Sub Main()
     Try
        Method1()
     Catch exceptionParameter As Exception
        Console.WriteLine(exceptionParameter.ToString())
        Console.WriteLine(exceptionParameter.Message)
        Console.WriteLine(exceptionParameter.StackTrace)
        Console.WriteLine(exceptionParameter.InnerException.ToString())
     End Try
  End Sub 
  Public Shared Sub Method1()
     Method2()
  End Sub
  Public Shared Sub Method2()
     Method3()
  End Sub
  Public Shared Sub Method3()
     Try
        Convert.ToInt32("Not an integer")
     Catch formatException As FormatException
        Throw New Exception("Exception occurred in Method3", _
           formatException)
     End Try
  End Sub

End Class</source>

System.Exception: Exception occurred in Method3 ---> System.FormatException: Input string was not in
 a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFor
matInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at Tester.Method3()
   --- End of inner exception stack trace ---
   at Tester.Method3()
   at Tester.Main()
Exception occurred in Method3
   at Tester.Method3()
   at Tester.Main()
System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFor
matInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at Tester.Method3()