How to use the Try/Catch block to catch exceptions in VB.NET

2 Answers

0 votes
Imports System.IO

Module Module1

    Sub Main()

        Try

            Dim sr As StreamReader = File.OpenText("c:\\data.txt")
            Console.WriteLine("The first text:  {0}", sr.ReadLine())
            sr.Close()

        Catch e As Exception

            Console.WriteLine("{0} - {1}", e.GetType(), e.Message)

        End Try

    End Sub

End Module

' run:
' 
' System.IO.FileNotFoundException - Could not find file 'c:\data.txt'.

 



answered Apr 9, 2016 by avibootz
0 votes
Imports System.IO

Module Module1

    Sub Main()

        Try

            Dim sr As StreamReader = File.OpenText("c:\\data.txt")
            Console.WriteLine("The first text:  {0}", sr.ReadLine())
            sr.Close()

        Catch e As Exception

            Console.WriteLine(e)

        End Try

    End Sub

End Module

' run:
' 
' System.IO.FileNotFoundException: Could not find file 'c:\data.txt'.
' File name: 'c:\data.txt'
'    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
'    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
' nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
' ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolea
' n useLongPath, Boolean checkHost)
'    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
' FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean
' bFromProxy, Boolean useLongPath, Boolean checkHost)
'    at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detec
' tEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
'    at System.IO.StreamReader..ctor(String path)
'    at System.IO.File.OpenText(String path)
'    at ConsoleApplication_Visual_Basic.Module1.Main() In D:\directx\ConsoleApplic
' ation_Visual_Basic\ ConsoleApplication_Visual_Basic \ Module1.vb: line 9

 



answered Apr 9, 2016 by avibootz

Related questions

2 answers 430 views
2 answers 297 views
1 answer 217 views
1 answer 197 views
197 views asked Dec 17, 2016 by avibootz
1 answer 218 views
218 views asked Jan 22, 2021 by avibootz
2 answers 420 views
420 views asked May 4, 2015 by avibootz
6 answers 682 views
682 views asked May 4, 2015 by avibootz
...