|
-
Aug 5th, 2000, 04:23 PM
#1
Thread Starter
Fanatic Member
Hi.
Originally posted by Megatron
I prefer to use Error Handling as a last resort
Megatron, does this mean that you don't even put in the statement at all? Or does it mean that you put the Error Handling in your programs, but only rely on it to fire as a last resort?
I'm asking this because you have more experience than I do and I wanted to know which technique you used.
Of course, everyone is welcome to chime in with their thoughts on this topic.
Thanks.
-
Aug 5th, 2000, 04:38 PM
#2
transcendental analytic
I agree on that error handling should be used as a last resort; it's awkward to use and makes your code unorganaized. I'm always searching for a way to prevent the errors to happen at all.
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
-
Aug 5th, 2000, 04:39 PM
#3
I usually use On Error Resume Next but On Error Goto Err is also useful. Its useful if there's an error and you use email to send yourself an email that the program may have bugs.
Code:
On Error Goto ErrorTrap
'code
Exit Sub
ErrorTrap:
Open App.path & "\log.log" For Append As #1
Print #1, Err.Number & " - " & Error$
Close #1
'End Sub
Error Handling is good for a lot of stuff, even though I only named one .
-
Aug 5th, 2000, 06:36 PM
#4
Yes, there are some cases where I use On Error GoTo, but basically, I try to avoid it when possible. You want to get rid of Error's not just ignore them.
Here is a perfect example; say I wanted to scroll through the items in a ListBox (using a Timer).
Here is one way:
Code:
Private Sub Timer1_Timer()
On Error Resume Next
List1.ListIndex = List1.ListIndex + 1
End Sub
Here is another:
Code:
Private Sub Timer1_Timer()
List1.ListIndex = List1.ListIndex + 1
If List1.Selected(List1.ListCount - 1) = True Then Timer1.Enabled = False
End Sub
-
Aug 5th, 2000, 10:03 PM
#5
Thread Starter
Fanatic Member
Thanks everyone, but
I need to make this a little clearer I believe.
If you are sure that a procedure doesn't have errors (and can't have errors based on the flawless logic it contains), is it even necessary to put error handling it it? I know that it sounds strange to ask this, but I would like to know what is considered to be standard programming procedure regarding this.
Thx.
-
Aug 5th, 2000, 10:31 PM
#6
If you are certain that a routine can not have errors then you don't need error handling, but why not do it anyhow. Most of my routines have the following code:
Code:
Public SomeRoutine()
On Error GoTo ErrorRoutine
' routine's code
Exit Sub
ErrorRoutine:
DisplayError "SomeRoutine"
End Sub
Public Sub DisplayError(sRoutine As String)
'***************************************************************************
'Purpose: Common error display routine
'Inputs: None
'Outputs: None
'***************************************************************************
MsgBox "Error #" & Str(Err.Number) & " was generated by " & Err.Source & " in routine " & sRoutine & "." & vbCrLf & vbCrLf & Err.Description, _
vbExclamation, , Err.HelpFile, Err.HelpContext
End Sub
Sure it's a bit of a bother to include the error handeling code, but it's easy enough to create a template and use that template each time you create a new routine.
With all due respect to some of the other people who responded, I think that a statement like "error handling should be used as a last resort" does a disservice to people who are trying to learn how to program in VB.
-
Aug 5th, 2000, 10:55 PM
#7
Thread Starter
Fanatic Member
Thanks Martin...
The code example was good too.
-
Aug 6th, 2000, 07:12 PM
#8
Fanatic Member
Martin Liss
With all due respect to some of the other people who responded, I think that a statement like "error handling should be used as a last resort" does a disservice to people who are trying to learn how to program in VB.
I agree with Martin Liss, and one thing that kinda pops up often is that error handlers are declared ...
Code:
On Error Goto SomeHandlerOrOther
and in many instances not closed
Code:
On Error Goto 0
Exit Sub
just thought i'd chip my bit in.....
DocZaf
{;->
-
Aug 6th, 2000, 08:42 PM
#9
I'm very surprised to read statements like "I use error handling as a last resort" from developers at this forum.
At my company we discard every procedure that lacks error handling. We just wouldn't present it to our customers.
Today when where all moving to thinner clients and n-tier development, and more and more to the Net, there are just to many bottlenecks and things that can fail.
Just think of a 3-tier application. You have the database server, the application server and the network it self to consider.
But even in a small desktop application there may be so many things that can fail.
Picture a small app that mimics the DOS copy command.
With DOS copy you can easily concatenate two files into one in the following manner:
COPY FILE1.DAT+FILE2.DAT FILE3.DAT
To mimic this behaviour you just have to follow these simple steps:
[list=1][*] Verify that the source is valid.[*] Delete the destination file if it already exists.[*] Open both source files for binary access (READ).[*] Open the destination file for binary access (WRITE).[*] Read the source into a buffer.[*] Write the buffer to the destination file.[*] Repeat the last two steps, as needed.[*] Close all files.[/list=1]
This is pretty straightforward. However, the devil is in the details, and file operations involve plenty of details.
Errors can occur at nearly every stage of this process.
Personally I also like to use (and treat) errors as exceptions. To use the example by Megatron above (about scrolling through the values in a ListBox using a Timer) I would have written the code in the following way:
Code:
Private Sub Timer1_Timer()
On Error Resume Next
List1.ListIndex = List1.ListIndex + 1
If Err Then
Timer1.Enabled = False
End If
End Sub
There are actually some benefits to this instead of doing the check that Megatron supplied:
Code:
If List1.Selected(List1.ListCount - 1) = True Then
Timer1.Enabled = False
End If
In my example you check the Err object Value property for a Long integer value. This means that you only checking one property value from one object.
In the other example you are actually checking two property values (Selected and ListCount).
It takes VB a lot longer to check property values than simple variable values.
But that is just two different coding styles and I didn't mean to put Megatron down in any way.
But my humble opinion is that you should ALWAYS add error-checking code.
Start doing it from the beginning in all your small apps so you make a habit of it.
You will gain a lot of debugging time in the end. Time you can spend marketing and make a profit of your coding.
Best regards
-
Aug 6th, 2000, 08:57 PM
#10
Fanatic Member
As i was saying....
[quote]
Personally I also like to use (and treat) errors as exceptions. To use the example by Megatron above (about scrolling through the values in a ListBox using a Timer) I would have written the code in the following way:
Code:
Private Sub Timer1_Timer()
On Error Resume Next
List1.ListIndex = List1.ListIndex + 1
If Err Then
Timer1.Enabled = False
End If
End Sub
And just like Joacim said,
But that is just two different coding styles and I didn't mean to put Megatron down in any way
and likewise, me him neither...
but he forgot the On Error Goto 0 as without this line the error handler is not turned of and i'm not 100% sure, but if you then declare aanother then its just added and activated but not de-activated.
Code:
Private Sub Timer1_Timer()
On Error Resume Next
List1.ListIndex = List1.ListIndex + 1
If Err Then
Timer1.Enabled = False
End If
'alwaze turn the handler of when your done with it
On Error Goto 0
End Sub
DocZaf
{;->
-
Aug 7th, 2000, 01:18 AM
#11
Well ....
So there are different views on whether to include error handling in your code or not. Some say an error-handling routine means you have not debugged your code (or atleast something to that effect) while some say that error-handling is an integral part of every piece of code that you write (and code without error handling is discarded).
With all due respect to both the extreme cases, let me say that you require error-handling in your code, though not necessarily in each and every routine. In procedures where you are confident there will be no errors, you can leave the error-handling out. But in procedures which are prone to errors, such as those which deal with opening and closing files, initializing and closing object references etc. it is advisable to add an error-handler.
The whole purpose behind an error-handling code is to prevent your application from crashing without any sensible warning or indication to the user. Though we have debugged and tested the code thoroughly again and again, it is better to include an error handler so that it won't crash on the client's PC under any circumstances.
I include in my project an error-handler which neatly displays the error number, description and source onto a form and also displays some possible method to avoid that error. The user is offered to choices, to continue or to stop. If he chooses to continue, the application will try to continue in spite of the error. At the same time the error is displayed to the user, it is also logged into an Errors.Log file along with the date and time, procedure in which the error occurred and the activity that was going on when the error occurred. This file is useful to the developers for debugging.
Also there are some cases where you just have to use the On Error ... statement. For e.g. the following piece of code checks for the existance of a file (the code is perhaps crude, but it's straightforward)
Code:
private sub CheckFile(strFileName as string)
if filelen(strfilename)=0 then
msgbox "This file does not exist")
endif
end sub
In this code, the hitch is that if strFileName really does not exist, the FileLen() will return an error. Even this error indicates that the file does not exist. So I can rewrite the above code as
Code:
private sub CheckFile(strFileName as string)
on error resume next
if filelen(strFileName)=0 then
msgbox "This file does not exist"
endif
end sub
Errors may crop up from unexpected places and you have to deal with them just the same. It may happen that the user accidentally deleted a file required by your program. Now when your program accesses that file an error occurs. To prevent this error from occuring, you cannot include code to check for the existence of the file first and then accessing it, as it will reduce the speed of your application. It is better to trap the error and then identify that a file is missing. This way if the file exists, you don't waste time checking for its existence.
After all, why do you purchase insurance when you very well know that you are not planning to die in the next couple of years?
-
Aug 7th, 2000, 09:16 AM
#12
Originally posted by Zaf Khan
he forgot the On Error Goto 0
All error handling must be contained in the procedure that uses On Error Goto ... or On Error Resume ...
That means that the error handling is automatically turned off when the procedure exits. So you don't really need to put an On Error Goto 0 in the end of a procedure, VB does this anyway by design.
You may dispute that it's good programming practise to do so anyway and I wont argue with that, but as I said it's not really necassary.
You do want to turn the error handling off in some cases though.
Because the error handling is passed thru the calling chain.
Here's an example:
Code:
Private Sub FirstProcedure()
On Error Resume Next
'do some stuff and assume that
'no error is raised.
Call SecondProcedure 'You haven't reached the exit point
'yet so the above error handling is
'still in effect
End Sub 'exit point. Error handling is turned of by VB
Private Sub SecondProcedure()
'No error handling in this procedure
Dim iResult as Integer
iResult = 5 / 0 'division by zero an error is raised
'and because the error handling in the
'first procedure is still active VB returns
'to the next line. That is the line after
'the line that called this procedure.
'i.e. It returns to the first procedure.
'this line of code will NEVER be executed.
MsgBox Err.Number & vbCrLf & Err.Description
End Sub
In the above case you would like to add On Error Goto 0 in the first procedure, just before the call to the second procedure.
Or (which is much better) you add error trapping code to the second procedure as well.
Best regards
[Edited by Joacim Andersson on 08-07-2000 at 10:18 AM]
-
Aug 7th, 2000, 09:56 AM
#13
Some of you might have misunderstood me. I said I try to avoid it when possible.
Using this code:
Code:
List1.ListIndex = List1.ListIndex + 1
If List1.Selected(List1.ListCount - 1) = True Then Timer1.Enabled = False
Is a lot more cleaner than using this code:
Code:
On Error Resume Next
List1.ListIndex = List1.ListIndex + 1
But in a case such as the following, it's easiest just to use Error Handling.
Code:
On Error GoTo ErrHandler
Open "MyTextFile.txt" For Input As #1
Text1.Text = Input(LOF(1), 1)
Close #1
ErrHandler:
If Err.Number = 53 Then Call MsgBox("File not found")
-
Aug 8th, 2000, 03:58 AM
#14
Fanatic Member
Martin
Sure it's a bit of a bother to include the error handeling code, but it's easy enough to create a template and use that template each time you create a new routine.
Do you mean like a procedure wrapper in Access?
How do you go about doing this?
-
Aug 8th, 2000, 09:24 AM
#15
In VB6:
1. Start a new project and add a module
2. Create a subroutine in the module that will serve as the template. The module might look somthing like this
Code:
Public Sub MySub()
'***************************************************************************
'Purpose:
'Inputs:
'Outputs:
'***************************************************************************
On Error GoTo ErrorRoutine
Exit Sub
ErrorRoutine:
CallMyCommonErrorHandler "MySub"
End Sub
3. Save the module in ...Program Files\Microsoft Visual Studio\VB98\Template\Code
Then when you want to add the routine to a project
4. Click the Tools>Add Code Snippet menu item
5. Select the bas file you just created.
In VB5 you would just do step 2 and then save and retrieve the bas file from some place that you'll remember.
-
Aug 8th, 2000, 09:53 AM
#16
Fanatic Member
-
Aug 11th, 2000, 11:25 AM
#17
New Member
Anyone interested in using a sweet tool for error handling should check this link
http://www1.jovesoft.com/Products/VBErrHandler.htm
This add in will automatically add the code to each subroutine you're working in. Plus, you can have complete control over what the error handler does as well as different "template" erro handler code. Just push a button and the code is inserted. It works very well.
-
Aug 11th, 2000, 01:31 PM
#18
Fanatic Member
I believe that you should eleminate all errors in a procedure, and then add error handling just as a procaution.
Just my $0.02
Gwdash
-
Dec 13th, 2000, 03:02 PM
#19
New Member
error handler
Hi,
First; What is the best way to come to this web site and then signe in?
Second; I read all of the postings on error handling and I'm still confused.
I have a project that works well.
I enter type a name in a text box and press the enter button.
The Name goes to a sequential file. It works; even when I print it; but now I'm supposed to have the Enter button's code (a) check for a comma followed by a space in the textbox. example( Tate, Mark )if there is no comma generate an appropriate error message if the comma and sapce are not found and terminate the enter procedure; and then also provide an error handler if there is no no disk in A: The handler is supposed to display a message with only the OK button and then allow the user to complete the Enter operation.
How do I do that?
Mark
Originally posted by yzfr1owner
Anyone interested in using a sweet tool for error handling should check this link
http://www1.jovesoft.com/Products/VBErrHandler.htm
This add in will automatically add the code to each subroutine you're working in. Plus, you can have complete control over what the error handler does as well as different "template" erro handler code. Just push a button and the code is inserted. It works very well.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|