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

K

Keith Kowalski

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
 
W

William Ryan eMVP

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/archive/2004/07/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/netrefactorproducthome.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/community/newsgroups
 
K

Keith Kowalski

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top