Connecting Tech Pros Worldwide Forums | Help | Site Map

Try Catch error handling - New to VB.net (Need ASAP!)

Keith Kowalski
Guest
 
Posts: n/a
#1: Nov 20 '05
I anm opening up a text file reading the lines of the file that refer to a
tif image in that file, If the tif image does not exist I need it to send an
email stating that the file doesn't exist then skip this file and move onto
the next file (line).

If file is there then move to a sirectory.

Here is the code I have (Feel free to make corrections as needed. If
possible make changes in red)

'Most Declarations are made as Public String or integer



Dim oDirInfo As DirectoryInfo = New DirectoryInfo(strPath) 'Sets path to
Print Folder

Dim oFiles() As FileInfo = oDirInfo.GetFiles 'Gets File list
from Print Folder

Dim oFile As FileInfo



For Each oFile In oDirInfo.GetFiles

'Gets only files that have an 'lst' extension

If oFile.Name.Substring(oFile.Name.Length - 3) = "lst" Then

'Adds the .lst file to the Listbox(1) along with the
path

ListBox1.Items.Add(strPath + oFile.Name)



strBatch = parseFileName(oFile.Name)

lblBatch.Text = "Batch: " & strBatch



lblBatch.Refresh()



'Sets strTPath as ListBox1.Items(0)

Dim strTPath As String = ListBox1.Items(0) 'IE:
atl26E_Batch.lst

'Show The Selected Item (0)

ListBox1.SelectedIndex = 0



'Sets StreamReader to Read Lines of the lst File

'strTPath is the first Item in ListBox1

Dim objStreamReader As System.IO.StreamReader = New
StreamReader(strTPath)





'Read to end of file or blank line

Do Until objStreamReader.Peek = -1

Try

strLine = objStreamReader.ReadLine()

' Exit the Loop if line is blank, signaling end
of file

If strLine = "" Then

Exit Do

Else



'myString equals the Line of Text from lst
File

Dim myString As String = strLine
'Filename.tif



' Remove Quotes (") From a string

strLine =
strLine.Replace(ControlChars.Quote, String.Empty)



'Puts location of file and line text (Image
Name) into ListBox2

'ie: C:\printImages\07162004\
atl26E_Batch\Image1.tif

ListBox2.Items.Add(strPrintFolder & strLine)



'Wait 1 second(s) for process to catch up

Thread.Sleep(1000)



'Keep count of number of images into
ListBox2

xCount = xCount + 1



'Refresh Listbox2 to display current Images

ListBox2.Refresh()



End If



Catch ex As Exception 'Not in correct Location

'Catch the error and display it.

strErrorMessage = "The following InnerException
reported: " & _

ex.InnerException.ToString()

'MessageBox.Show(IOExp.ToString)

MessageBox.Show(ex.ToString)

MessageBox.Show(ex.Message)

Emailit(strErrorMessage)

Exit Sub

End Try

Loop 'End Do Until loop





'Close StreamReader

objStreamReader.Close() 'Close the Streamreader

objStreamReader = Nothing 'Set Streamreader to Nothing




'************************************************* **********************

'>>> Create Directory for lst file and move to that
directory >>>


'************************************************* **********************



Dim strOfileName As String = oFile.Name

'Remove ".lst" From the File name

Dim strRemovelst As String =
strOfileName.Replace(".lst", String.Empty)

'set archive folder name + "d" + Date + File Naem -
".lst"

strMyDir = strArchiveFolder + "d" + myDateReplace +
strRemovelst



Dim strSubDir As String = strArchiveFolder +
myDateReplace + strRemovelst

Dim strCSubDir As String = strArchiveFolder +
myDateReplace + "\" + strRemovelst + "\"



' Make a reference to a directory.

Dim di As New DirectoryInfo(strArchiveFolder +
myDateReplace)

' Create the directory only if it does not already
exist.

If di.Exists = False Then

di.Create()

End If



' Create a subdirectory in the directory just created.

Dim dis As DirectoryInfo =
di.CreateSubdirectory(strRemovelst)

If dis.Exists = False Then

dis.Create()

'Move files to this directory

'Dim lstFileMove As FileInfo = New FileInfo(strPath
+ oFile.Name)

'lstFileMove.MoveTo(strCSubDir + strRemovelst +
".lst")

Else

'Move files to this directory

Dim lstFileMove As FileInfo = New FileInfo(strPath +
oFile.Name)

lstFileMove.MoveTo(strCSubDir + strRemovelst +
".lst")

End If



'Print Images, GoTO PrintImages Sub

' Calls a sub to print the images

PrintImages(strCSubDir, strRemovelst)





iCount = iCount + 1 'Keep track of
Images

ListBox2.Items.Clear() 'Clear the
Listbox(2)



End If

Next 'End For Next Loop





oFile = Nothing 'Set oFile to Nothing

ListBox1.Items.Clear() 'Clear Listbox(1)

ListBox2.Items.Clear() 'Clear Listbox(2)

lblBatch.Text = "Batch: "

Timer1.Enabled = True 'Re-Enable the Timer (Starts
code from beginning)

End If


William Ryan eMVP
Guest
 
Posts: n/a
#2: Nov 20 '05

re: Try Catch error handling - New to VB.net (Need ASAP!)


Hi Keith:

I'm not sure exactly what the problem is but here are a few suggestions:

You can use .GetFiles("*.lst") to just get the files ending in .lst - this
could reduce one of the if's.
You are wrapping way too much code in a Try Catch and you are catching
System.Exception. While there are some legitimate scenarios to catch
System.Exception, they are few and far between. Essentially trapping an
exception says "I know that there is the possiblility of something outside
of my control happening that will cause me some headaches. When this
specific problem happens I'm going to respond to it directly by doing _____"

System.Exception will catch everythign, EVERYTHING, OutOfMemoryException,
StackOverflow, everything. If you must use it, you'll probably want to trap
System.IO.IoException first, and perhaps IndexOutOfRange. Also, seldom will
you need to wrap more than a few lines in a try catch. If you do you're
trying wayy too much.

As far as closing those streamreaders and disposing them, you'll probably
want to put that in a Finally block. Remember that Finally executes always
and you don't want to risk leaving those resources open by an exception.
Also, with each of those Move statements for instance, you'll probably want
to trap those specifically so that if one works but the others don't you can
undo the move to or take some other corrective action. In the Upcoming
release of Visual studio .NET the TransactionScope object will be able to
work with the filesystem (here's an example using a DB Transaction, but the
same will work (hopefully) with the filesystem when it's finally released
http://msmvps.com/williamryan/archiv...7/08/9759.aspx)

I'm not sure what your emailit code looks like but the same holds there,
make sure you trap as specifically as possible. Also, you may want to try
to reduce the number here in the main method - make some functions out of
them so it will be easier to maintain. If you check out www.knowdotnet.com
you can download .NET Refactor
http://www.knowdotnet.com/articles/n...oducthome.html for free for
the trial period. It will not only help you extract the methods, but it
will analyze cyclomatic complexity for you and give you some hints in that
regard. We have a free 30 day trial on it so even if you don't need a
refactoring tool, it could definitely help you clean up the method (for
instance, you could decide to extract things down to say 20 lines of code
per method or some similar rule).

If I didn't answer your question though please let me know and I'll do what
I can.

HTH,

Bill

--

W.G. Ryan, eMVP

Have an opinion on the effectiveness of Microsoft Embedded newsgroups?
Let Microsoft know!
https://www.windowsembeddedeval.com/...ity/newsgroups
"Keith Kowalski" <keith@rdfs.com> wrote in message
news:%23opWzb1aEHA.3524@TK2MSFTNGP12.phx.gbl...[color=blue]
> I anm opening up a text file reading the lines of the file that refer to a
> tif image in that file, If the tif image does not exist I need it to send[/color]
an[color=blue]
> email stating that the file doesn't exist then skip this file and move[/color]
onto[color=blue]
> the next file (line).
>
> If file is there then move to a sirectory.
>
> Here is the code I have (Feel free to make corrections as needed. If
> possible make changes in red)
>
> 'Most Declarations are made as Public String or integer
>
>
>
> Dim oDirInfo As DirectoryInfo = New DirectoryInfo(strPath) 'Sets path to
> Print Folder
>
> Dim oFiles() As FileInfo = oDirInfo.GetFiles 'Gets File[/color]
list[color=blue]
> from Print Folder
>
> Dim oFile As FileInfo
>
>
>
> For Each oFile In oDirInfo.GetFiles
>
> 'Gets only files that have an 'lst' extension
>
> If oFile.Name.Substring(oFile.Name.Length - 3) = "lst"[/color]
Then[color=blue]
>
> 'Adds the .lst file to the Listbox(1) along with the
> path
>
> ListBox1.Items.Add(strPath + oFile.Name)
>
>
>
> strBatch = parseFileName(oFile.Name)
>
> lblBatch.Text = "Batch: " & strBatch
>
>
>
> lblBatch.Refresh()
>
>
>
> 'Sets strTPath as ListBox1.Items(0)
>
> Dim strTPath As String = ListBox1.Items(0) 'IE:
> atl26E_Batch.lst
>
> 'Show The Selected Item (0)
>
> ListBox1.SelectedIndex = 0
>
>
>
> 'Sets StreamReader to Read Lines of the lst File
>
> 'strTPath is the first Item in ListBox1
>
> Dim objStreamReader As System.IO.StreamReader = New
> StreamReader(strTPath)
>
>
>
>
>
> 'Read to end of file or blank line
>
> Do Until objStreamReader.Peek = -1
>
> Try
>
> strLine = objStreamReader.ReadLine()
>
> ' Exit the Loop if line is blank, signaling[/color]
end[color=blue]
> of file
>
> If strLine = "" Then
>
> Exit Do
>
> Else
>
>
>
> 'myString equals the Line of Text from lst
> File
>
> Dim myString As String = strLine
> 'Filename.tif
>
>
>
> ' Remove Quotes (") From a string
>
> strLine =
> strLine.Replace(ControlChars.Quote, String.Empty)
>
>
>
> 'Puts location of file and line text[/color]
(Image[color=blue]
> Name) into ListBox2
>
> 'ie: C:\printImages\07162004\
> atl26E_Batch\Image1.tif
>
> ListBox2.Items.Add(strPrintFolder &[/color]
strLine)[color=blue]
>
>
>
> 'Wait 1 second(s) for process to catch up
>
> Thread.Sleep(1000)
>
>
>
> 'Keep count of number of images into
> ListBox2
>
> xCount = xCount + 1
>
>
>
> 'Refresh Listbox2 to display current[/color]
Images[color=blue]
>
> ListBox2.Refresh()
>
>
>
> End If
>
>
>
> Catch ex As Exception 'Not in correct Location
>
> 'Catch the error and display it.
>
> strErrorMessage = "The following[/color]
InnerException[color=blue]
> reported: " & _
>
> ex.InnerException.ToString()
>
> 'MessageBox.Show(IOExp.ToString)
>
> MessageBox.Show(ex.ToString)
>
> MessageBox.Show(ex.Message)
>
> Emailit(strErrorMessage)
>
> Exit Sub
>
> End Try
>
> Loop 'End Do Until loop
>
>
>
>
>
> 'Close StreamReader
>
> objStreamReader.Close() 'Close the Streamreader
>
> objStreamReader = Nothing 'Set Streamreader to[/color]
Nothing[color=blue]
>
>
>
>
> '************************************************* **********************
>
> '>>> Create Directory for lst file and move to that
> directory >>>
>
>
> '************************************************* **********************
>
>
>
> Dim strOfileName As String = oFile.Name
>
> 'Remove ".lst" From the File name
>
> Dim strRemovelst As String =
> strOfileName.Replace(".lst", String.Empty)
>
> 'set archive folder name + "d" + Date + File Naem -
> ".lst"
>
> strMyDir = strArchiveFolder + "d" + myDateReplace +
> strRemovelst
>
>
>
> Dim strSubDir As String = strArchiveFolder +
> myDateReplace + strRemovelst
>
> Dim strCSubDir As String = strArchiveFolder +
> myDateReplace + "\" + strRemovelst + "\"
>
>
>
> ' Make a reference to a directory.
>
> Dim di As New DirectoryInfo(strArchiveFolder +
> myDateReplace)
>
> ' Create the directory only if it does not already
> exist.
>
> If di.Exists = False Then
>
> di.Create()
>
> End If
>
>
>
> ' Create a subdirectory in the directory just created.
>
> Dim dis As DirectoryInfo =
> di.CreateSubdirectory(strRemovelst)
>
> If dis.Exists = False Then
>
> dis.Create()
>
> 'Move files to this directory
>
> 'Dim lstFileMove As FileInfo = New[/color]
FileInfo(strPath[color=blue]
> + oFile.Name)
>
> 'lstFileMove.MoveTo(strCSubDir + strRemovelst +
> ".lst")
>
> Else
>
> 'Move files to this directory
>
> Dim lstFileMove As FileInfo = New FileInfo(strPath[/color]
+[color=blue]
> oFile.Name)
>
> lstFileMove.MoveTo(strCSubDir + strRemovelst +
> ".lst")
>
> End If
>
>
>
> 'Print Images, GoTO PrintImages Sub
>
> ' Calls a sub to print the images
>
> PrintImages(strCSubDir, strRemovelst)
>
>
>
>
>
> iCount = iCount + 1 'Keep track of
> Images
>
> ListBox2.Items.Clear() 'Clear the
> Listbox(2)
>
>
>
> End If
>
> Next 'End For Next Loop
>
>
>
>
>
> oFile = Nothing 'Set oFile to Nothing
>
> ListBox1.Items.Clear() 'Clear Listbox(1)
>
> ListBox2.Items.Clear() 'Clear Listbox(2)
>
> lblBatch.Text = "Batch: "
>
> Timer1.Enabled = True 'Re-Enable the Timer (Starts
> code from beginning)
>
> End If
>
>[/color]


Keith Kowalski
Guest
 
Posts: n/a
#3: Nov 20 '05

re: Try Catch error handling - New to VB.net (Need ASAP!)


You may have not answered my question specifically, but you gave me alot to
look at, I will try to break up the code a bit and wrap less code in my try
catch ... I think this should keep me busy.. In simple terms what I was
looking for is in a loop, lets say you are reading lines of text ...
line 1: hello
line 2: "This breaks, causes a Catch
line 3: World

i need the code to send an email (Email code is working fine) about the
error, then skip this line, file, etc.... and continue on with the loop.

Thank you for your help and advice,
Keith K. Kowalski

"William Ryan eMVP" <dotnetguru@comcast.nospam.net> wrote in message
news:%232fkHL2aEHA.716@TK2MSFTNGP11.phx.gbl...[color=blue]
> Hi Keith:
>
> I'm not sure exactly what the problem is but here are a few suggestions:
>
> You can use .GetFiles("*.lst") to just get the files ending in .lst -[/color]
this[color=blue]
> could reduce one of the if's.
> You are wrapping way too much code in a Try Catch and you are catching
> System.Exception. While there are some legitimate scenarios to catch
> System.Exception, they are few and far between. Essentially trapping an
> exception says "I know that there is the possiblility of something outside
> of my control happening that will cause me some headaches. When this
> specific problem happens I'm going to respond to it directly by doing[/color]
_____"[color=blue]
>
> System.Exception will catch everythign, EVERYTHING, OutOfMemoryException,
> StackOverflow, everything. If you must use it, you'll probably want to[/color]
trap[color=blue]
> System.IO.IoException first, and perhaps IndexOutOfRange. Also, seldom[/color]
will[color=blue]
> you need to wrap more than a few lines in a try catch. If you do you're
> trying wayy too much.
>
> As far as closing those streamreaders and disposing them, you'll probably
> want to put that in a Finally block. Remember that Finally executes[/color]
always[color=blue]
> and you don't want to risk leaving those resources open by an exception.
> Also, with each of those Move statements for instance, you'll probably[/color]
want[color=blue]
> to trap those specifically so that if one works but the others don't you[/color]
can[color=blue]
> undo the move to or take some other corrective action. In the Upcoming
> release of Visual studio .NET the TransactionScope object will be able to
> work with the filesystem (here's an example using a DB Transaction, but[/color]
the[color=blue]
> same will work (hopefully) with the filesystem when it's finally released
> http://msmvps.com/williamryan/archiv...7/08/9759.aspx)
>
> I'm not sure what your emailit code looks like but the same holds there,
> make sure you trap as specifically as possible. Also, you may want to try
> to reduce the number here in the main method - make some functions out of
> them so it will be easier to maintain. If you check out[/color]
www.knowdotnet.com[color=blue]
> you can download .NET Refactor
> http://www.knowdotnet.com/articles/n...oducthome.html for free[/color]
for[color=blue]
> the trial period. It will not only help you extract the methods, but it
> will analyze cyclomatic complexity for you and give you some hints in that
> regard. We have a free 30 day trial on it so even if you don't need a
> refactoring tool, it could definitely help you clean up the method (for
> instance, you could decide to extract things down to say 20 lines of code
> per method or some similar rule).
>
> If I didn't answer your question though please let me know and I'll do[/color]
what[color=blue]
> I can.
>
> HTH,
>
> Bill
>
> --
>
> W.G. Ryan, eMVP
>
> Have an opinion on the effectiveness of Microsoft Embedded newsgroups?
> Let Microsoft know!
> https://www.windowsembeddedeval.com/...ity/newsgroups
> "Keith Kowalski" <keith@rdfs.com> wrote in message
> news:%23opWzb1aEHA.3524@TK2MSFTNGP12.phx.gbl...[color=green]
> > I anm opening up a text file reading the lines of the file that refer to[/color][/color]
a[color=blue][color=green]
> > tif image in that file, If the tif image does not exist I need it to[/color][/color]
send[color=blue]
> an[color=green]
> > email stating that the file doesn't exist then skip this file and move[/color]
> onto[color=green]
> > the next file (line).
> >
> > If file is there then move to a sirectory.
> >
> > Here is the code I have (Feel free to make corrections as needed. If
> > possible make changes in red)
> >
> > 'Most Declarations are made as Public String or integer
> >
> >
> >
> > Dim oDirInfo As DirectoryInfo = New DirectoryInfo(strPath) 'Sets path[/color][/color]
to[color=blue][color=green]
> > Print Folder
> >
> > Dim oFiles() As FileInfo = oDirInfo.GetFiles 'Gets File[/color]
> list[color=green]
> > from Print Folder
> >
> > Dim oFile As FileInfo
> >
> >
> >
> > For Each oFile In oDirInfo.GetFiles
> >
> > 'Gets only files that have an 'lst' extension
> >
> > If oFile.Name.Substring(oFile.Name.Length - 3) = "lst"[/color]
> Then[color=green]
> >
> > 'Adds the .lst file to the Listbox(1) along with the
> > path
> >
> > ListBox1.Items.Add(strPath + oFile.Name)
> >
> >
> >
> > strBatch = parseFileName(oFile.Name)
> >
> > lblBatch.Text = "Batch: " & strBatch
> >
> >
> >
> > lblBatch.Refresh()
> >
> >
> >
> > 'Sets strTPath as ListBox1.Items(0)
> >
> > Dim strTPath As String = ListBox1.Items(0) 'IE:
> > atl26E_Batch.lst
> >
> > 'Show The Selected Item (0)
> >
> > ListBox1.SelectedIndex = 0
> >
> >
> >
> > 'Sets StreamReader to Read Lines of the lst File
> >
> > 'strTPath is the first Item in ListBox1
> >
> > Dim objStreamReader As System.IO.StreamReader = New
> > StreamReader(strTPath)
> >
> >
> >
> >
> >
> > 'Read to end of file or blank line
> >
> > Do Until objStreamReader.Peek = -1
> >
> > Try
> >
> > strLine = objStreamReader.ReadLine()
> >
> > ' Exit the Loop if line is blank, signaling[/color]
> end[color=green]
> > of file
> >
> > If strLine = "" Then
> >
> > Exit Do
> >
> > Else
> >
> >
> >
> > 'myString equals the Line of Text from[/color][/color]
lst[color=blue][color=green]
> > File
> >
> > Dim myString As String = strLine
> > 'Filename.tif
> >
> >
> >
> > ' Remove Quotes (") From a string
> >
> > strLine =
> > strLine.Replace(ControlChars.Quote, String.Empty)
> >
> >
> >
> > 'Puts location of file and line text[/color]
> (Image[color=green]
> > Name) into ListBox2
> >
> > 'ie: C:\printImages\07162004\
> > atl26E_Batch\Image1.tif
> >
> > ListBox2.Items.Add(strPrintFolder &[/color]
> strLine)[color=green]
> >
> >
> >
> > 'Wait 1 second(s) for process to catch[/color][/color]
up[color=blue][color=green]
> >
> > Thread.Sleep(1000)
> >
> >
> >
> > 'Keep count of number of images into
> > ListBox2
> >
> > xCount = xCount + 1
> >
> >
> >
> > 'Refresh Listbox2 to display current[/color]
> Images[color=green]
> >
> > ListBox2.Refresh()
> >
> >
> >
> > End If
> >
> >
> >
> > Catch ex As Exception 'Not in correct Location
> >
> > 'Catch the error and display it.
> >
> > strErrorMessage = "The following[/color]
> InnerException[color=green]
> > reported: " & _
> >
> > ex.InnerException.ToString()
> >
> > 'MessageBox.Show(IOExp.ToString)
> >
> > MessageBox.Show(ex.ToString)
> >
> > MessageBox.Show(ex.Message)
> >
> > Emailit(strErrorMessage)
> >
> > Exit Sub
> >
> > End Try
> >
> > Loop 'End Do Until loop
> >
> >
> >
> >
> >
> > 'Close StreamReader
> >
> > objStreamReader.Close() 'Close the Streamreader
> >
> > objStreamReader = Nothing 'Set Streamreader to[/color]
> Nothing[color=green]
> >
> >
> >
> >
> > '************************************************* **********************
> >
> > '>>> Create Directory for lst file and move to[/color][/color]
that[color=blue][color=green]
> > directory >>>
> >
> >
> > '************************************************* **********************
> >
> >
> >
> > Dim strOfileName As String = oFile.Name
> >
> > 'Remove ".lst" From the File name
> >
> > Dim strRemovelst As String =
> > strOfileName.Replace(".lst", String.Empty)
> >
> > 'set archive folder name + "d" + Date + File Naem -
> > ".lst"
> >
> > strMyDir = strArchiveFolder + "d" + myDateReplace +
> > strRemovelst
> >
> >
> >
> > Dim strSubDir As String = strArchiveFolder +
> > myDateReplace + strRemovelst
> >
> > Dim strCSubDir As String = strArchiveFolder +
> > myDateReplace + "\" + strRemovelst + "\"
> >
> >
> >
> > ' Make a reference to a directory.
> >
> > Dim di As New DirectoryInfo(strArchiveFolder +
> > myDateReplace)
> >
> > ' Create the directory only if it does not already
> > exist.
> >
> > If di.Exists = False Then
> >
> > di.Create()
> >
> > End If
> >
> >
> >
> > ' Create a subdirectory in the directory just[/color][/color]
created.[color=blue][color=green]
> >
> > Dim dis As DirectoryInfo =
> > di.CreateSubdirectory(strRemovelst)
> >
> > If dis.Exists = False Then
> >
> > dis.Create()
> >
> > 'Move files to this directory
> >
> > 'Dim lstFileMove As FileInfo = New[/color]
> FileInfo(strPath[color=green]
> > + oFile.Name)
> >
> > 'lstFileMove.MoveTo(strCSubDir + strRemovelst +
> > ".lst")
> >
> > Else
> >
> > 'Move files to this directory
> >
> > Dim lstFileMove As FileInfo = New[/color][/color]
FileInfo(strPath[color=blue]
> +[color=green]
> > oFile.Name)
> >
> > lstFileMove.MoveTo(strCSubDir + strRemovelst +
> > ".lst")
> >
> > End If
> >
> >
> >
> > 'Print Images, GoTO PrintImages Sub
> >
> > ' Calls a sub to print the images
> >
> > PrintImages(strCSubDir, strRemovelst)
> >
> >
> >
> >
> >
> > iCount = iCount + 1 'Keep track of
> > Images
> >
> > ListBox2.Items.Clear() 'Clear the
> > Listbox(2)
> >
> >
> >
> > End If
> >
> > Next 'End For Next Loop
> >
> >
> >
> >
> >
> > oFile = Nothing 'Set oFile to Nothing
> >
> > ListBox1.Items.Clear() 'Clear Listbox(1)
> >
> > ListBox2.Items.Clear() 'Clear Listbox(2)
> >
> > lblBatch.Text = "Batch: "
> >
> > Timer1.Enabled = True 'Re-Enable the Timer[/color][/color]
(Starts[color=blue][color=green]
> > code from beginning)
> >
> > End If
> >
> >[/color]
>
>[/color]


Closed Thread