472,779 Members | 2,502 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,779 software developers and data experts.

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

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
Nov 20 '05 #1
2 4357
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" <ke***@rdfs.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
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

Nov 20 '05 #2
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" <do********@comcast.nospam.net> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
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" <ke***@rdfs.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
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


Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Kim Haines | last post by:
I need help finding where an error is occuring in my code. I use a try-catch block like this in my global.asa: try { //my code } catch (e) { Application('errormsg') = ("An exception...
4
by: James Radke | last post by:
Hello, I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module...
8
by: CarpetMnuncher! | last post by:
================================================================= How do I use Try Catch error handling when a timer is involved? If I preform the preciduer below and I get an error I revive...
9
by: Gustaf | last post by:
I'm confused about structured error handling. The following piece of code is a simplification of a class library I'm working on. It works, and it does what I want, but I'm still not convinced that...
4
by: John Wright | last post by:
I need some good ideas or references for robust error handling in VB.NET. I am using try catch but find myself using the generic exception handler. I would like to get more precise error handling...
1
by: John | last post by:
Hi I have a winform app with try/catch error handling implemented in key areas. Problem is errors can occur in other areas in situations that I may not foresee. Is there a way to implemented a...
5
by: Blasting Cap | last post by:
I would like for a page in my app (asp.net framework 2.0, VS 2005) to both display a message to the user, as well as sending an email when an error occurs. I have code in the global.asax.vb...
0
by: dhyder | last post by:
I'm working on an admin page for a SQL Server 05 db. The page is in ASP.NET 2.0/C#. The db has multiple tables with foreign keys/constraints. I have multiple SqlDataSources and GridViews, which...
2
by: Omar Abid | last post by:
Reason of this project: Error handling is one of the most difficult thing that may afford a programmer. It isn't as easy as you think and handling errors in a program some time can make errors...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.