VB6 Error trapping with File opening

007bond
if I put a Close #1 in an error-trapping statement, what will happen if the script runs before or after the file was closed, will it produce another error? If I don't do this, then should a put a statement that will have VB return to where it was before the error, or just let my script run?

Alex
If your error handler needs to close a file, why not either use a different error handler for after you open the file, or otherwise set a boolean flag to specify whether to close the file?

Also I wouldn't recommend always using #1 as that can lead to clashes. You should use the FreeFile function to get a file handle number and store that in a variable. What I tend to do is this:


Dim FH as Integer
FH = FreeFile
Open "whatever.txt" For Input As #FH
.
.
.
Close #FH

007bond
How do I use two different error handlers? The only way I can think of is setting a boolean variable to true, and then checking for this in the error handling. Is there another way?

Alex
Yes that would work but you can also use "On Error Goto 0" to turn off error handling set earlier in a procedure. So you could have:


On Error Goto ErrorHandler1
' do stuff
On Error Goto 0

Open "blah.txt" For Input As ....

On Error Goto ErrorHandler2
' blah blah
On Error Goto 0

Close #FH
Exit Sub

ErrorHandler1:
MsgBox "Something nasty happened."
Resume Next

ErrorHandler2:
MsgBox "An error occurred while writing to the file..."
Close #FH

paul_one
You could also have one error handler, but you grab the error code and use that to decide what to do next (using a select case, or if). Or you can use a variable which sets where you are in the procedure and lets the error handler react that way.

There's loads of different ways to do things.

007bond
Thanks, I didn't realise that you could have multiple On Error statements in one procedure.

GameBoy
you really should try posting on VB forums. it helps more if you're arround 1000s of expert coders.

007bond
I've tried twice and had problems activating my account, so I gave up. vBulletin really makes it hard for you, especially if you want to change your email address. I've also had problems @ thegaminguniverse.com, which also uses vBulletin, but I haven't had any problems with the Legends Alliance Forums (forums.legendsalliance.com). Something is really screwy with vBulletin.

This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums