• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 217
  • Last Modified:

Error Handling Help !

I have 2 main questions .

1) Assuming that i want to read the context from  a:\text.txt , if the floppy is not inserted or the floppy cannot be read , it'll popup a runtime error . how can i display a msgbox instead of a runtime error msgbox ? i tried to use On Error Goto , but it will still popup the "please insert floppy" even though the floppy is in the drive , why ?
----
Dim fso As New FileSystemObject
Dim txtStream As TextStream
Dim strContent As String

Private Sub Form_Load()

On Error GoTo errhandler

Set txtStream = fso.OpenTextFile("a:\verify.txt", ForReading)
strContent = txtStream.ReadAll
MsgBox strContent

errhandler:
MsgBox "please insert floppy"
End Sub

------------------------

Question 2 :

a string "831030"
how can i extract to str1 =83 , str2=10 and str3=30 .
if i got a listbox contain the months (January , Feb , March ,...December) ,how to correspond the str2 to the listbox ? ie : if str2=2 then the listbox will automatically select February and so on..

thanks .
0
ANGWK
Asked:
ANGWK
  • 4
  • 4
  • 2
  • +5
1 Solution
 
crazymanCommented:
place exit sub before

errhandler:


exit sub
errhandler:
0
 
TimCotteeCommented:
Hi ANGWK,

Because you need Exit Sub between these lines as follows:

MsgBox strContent
Exit Sub

errhandler:


This means that it will only get to the error handler when an error is generated and that it is forced to exit sub if it completes the code normally.

As for part 2, this really is a seperate question and should be posted as such.

Please also now accept my comment in your previous question. Ideally you should have returned to that question for more information rather than starting a new one which follows on from the previous one that other experts may not have seen.

Tim Cottee MCSD, MCDBA, CPIM
http://www.timcottee.tk 

Brainbench MVP for Visual Basic
http://www.brainbench.com

Experts-Exchange Advisory Board Member
0
 
PiterCommented:

About Question 2:


Dim str As String
Dim rr As String
Dim rr1 As String
Dim rr2 As String
 
    str = "831030"
       
       rr = Mid(str, 1, Len(str) - 4)
       rr1 = Mid(str, 3, Len(str) - 4)
       rr2 = Mid(str, 5, Len(str) - 4)

       MsgBox rr   'Result is 83
       MsgBox rr1  'Result is 10
       MsgBox rr2 'Result is 30
     
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ANGWKAuthor Commented:
crazyman , Timcoffee , although i'v added the exit sub , yet it'll still popup the msgbox "Please insert floppy" , although there's no error . Please run the code and you'll know .

*TimCoffee which 1 do you mean ?
0
 
TheMekCommented:
The Exit Sub before the errorhandler should work as stated. Sure you placed it right?
If it's placed right check your code by remarking the On Error statement and see if and where an error occurs.

Cheers,
    Erwin
0
 
ANGWKAuthor Commented:
crazyman , Timcoffee , although i'v added the exit sub , yet it'll still popup the msgbox "Please insert floppy" , although there's no error . Please run the code and you'll know .

*TimCoffee which 1 do you mean ?
0
 
cyberknetCommented:
This is not an answer. Please do not accept it as an answer. This is merely a best practice suggestion.

For all those who say to use Exit Sub (And would probably recommend Exit Function and End too):

This is very bad coding practice. Anyone who has come from a C/C++ background will tell you that there should be one way into a function, and one way out.

There is no excuse for laziness in code. If-Then-Else blocks are exceptionally easy to write. Select Case is cleaner, and even faster.

Observe:

Dim fso As New FileSystemObject
Dim txtStream As TextStream
Dim strContent As String

[Alternate End 1:]
errhandler:
    if err.number <> 0 then
        MsgBox "please insert floppy"
    end if

[Alternate End 2:]
errhandler:
    Select Case Err.Number
        Case 0
        Case Else
            MsgBox "please insert floppy"
    end if

ideally, you would want to test the actual number and make sure that that was really the error encountered. (was it a missing floppy, was it a file not found, was it a network error etc etc)

Please do not encourage sloppy coding practices.
0
 
ANGWKAuthor Commented:
crazyman , Timcoffee , although i'v added the exit sub , yet it'll still popup the msgbox "Please insert floppy" , although there's no error . Please run the code and you'll know .

*TimCoffee which 1 do you mean ?
0
 
charlobCommented:
cyberknet:

errhandler:
   Select Case Err.Number
       Case 0
       Case Else
           MsgBox "please insert floppy"
   End if    <---------------Sloppy coding??????? ;P
0
 
TimCotteeCommented:
Cyberknet, please don't jump to conclusions.

In your methodology, given the lack of C++ style error handling in VB6, you would need to use on error resume next, this would mean that by the time you actually reached your error handler at the end of the code segment it is highly likely that you will have raised additional errors due to the first failure. This would actually obscure the fault and prevent adequate handling of the error that was originally raised.

I can accept the point that there should be one way in and one way out of routine and that there are always other ways to code something. However Exit Sub/Exit Function are a completely different thing to END which I abhor!

As a matter of fact I would personally strongly deprecate the use of the filesystemobject in VB under any circumstances but having decided to go with this I am not going to start criticising that choice at this point.

VB is not C++ and any comparison between the two and the coding necessary to achieve a desired aim is invidious.
0
 
CimperialiCommented:
By the way, you sure you have the "verify.txt" in the root of your floppy?

Set txtStream = fso.OpenTextFile("a:\verify.txt", ForReading)
0
 
ANGWKAuthor Commented:
well , indeed an expert :) yours really works !
0
 
CimperialiCommented:
play with this code:
Option Explicit
'I do prefer to declare with full names
Private fso As Scripting.FileSystemObject
Dim strContent As String

Private Sub Form_Load()
Dim theDrive As Scripting.Drive
Dim txtStream As Scripting.TextStream
Dim retAnswer As VbMsgBoxResult
Dim intFree As Integer

On Error GoTo errhandler
'do prefer to know where and when I instantiate objects...
Set fso = New FileSystemObject
'check if an "a:" drive exists
If fso.DriveExists("a:") Then
   Set theDrive = fso.GetDrive("a:")
   If theDrive.IsReady Then
      'yes, you can read from it
      If theDrive.DriveType = Removable Then
         'yes, it may be a floppy drive
         'and now let us see if there is the file you where looking for
         If Dir("a:\verify.txt") <> "" Then
            On Error GoTo 0
            On Error Resume Next
            Set txtStream = fso.OpenTextFile("a:\verify.txt", ForReading)
            If Err.Number <> 0 Then
               MsgBox "unable to open using ""Set txtStream = fso.OpenTextFile"" " & vbCrLf & Err.Description
               Err.Clear
            Else
               strContent = txtStream.ReadAll
               MsgBox strContent
               txtStream.Close
               Set txtStream = Nothing
               
            End If
         Else
            retAnswer = MsgBox("Drive is fine, floppy is in; but I cannot find the ""a:\verify.txt"" file!" & vbCrLf & "Do you want me to try to create it?", vbYesNo)
            If retAnswer = vbYes Then
               On Error GoTo 0
               On Error Resume Next
               intFree = FreeFile
               Open "a:\verify.txt" For Output As #intFree
               Close #intFree
               If Err.Number <> 0 Then
                  MsgBox "Unable to create the file" & vbCrLf & Err.Description
                  Err.Clear
               End If
            End If
         End If
      Else
         MsgBox "Once I will meet you and you will catch the devil!You assigned ""a:"" letter to a non removable media!!"
      End If
   Else
      MsgBox "Ehy, did you forget to put in a floppy?"
   End If
Else
   'the "a:" drive does not exists
   MsgBox "You renamed the floppy drive. Developer has to code more to find it..."
End If
'free resources

Set theDrive = Nothing
Set fso = Nothing
End Sub


0
 
CimperialiCommented:
By the way:
in Vb it exists
On Error Goto
and it is really useful.

Exit do, exit function, etc. are useful in many cases. For a debate on this topic search fro the author of "Hardcode Visual Basic". You may discover something you did not thought...
0
 
CimperialiCommented:
Sorry, it was the author of "Hardcore Visual Basic" (Bruce McKinney)
0
 
cyberknetCommented:
TimCottee:
[quote]
In your methodology, given the lack of C++ style error handling in VB6, you would need to use on error resume next, this would mean that by the time you actually reached your error handler at the end of the code segment it is highly likely that you will have raised additional errors due to the first failure. This would actually obscure the fault and prevent adequate handling of the error that was originally raised.
[/quote]


That is not true. Please do not jump to conclusions. You would use On Error Goto (label). Once the error has been handled, the coder can either Resume, Resume Next, or let the function exit naturally if the error handler is at the bottom of the function. I always put my error handler there, it makes for a nice flow if an error is not recoverable.

On Error Resume Next should be used infrequently and in very specific circumstance. Rarely would I recommend anyone to use this. On Error Goto (label) is a much more robust, reliable method. It is entirely compatible with the methodology that I posted.

[quote]
As a matter of fact I would personally strongly deprecate the use of the filesystemobject in VB under any circumstances but having decided to go with this I am not going to start criticising that choice at this point.
[/quote]
I think that it is definitely an expert's responsibility to ensure that other experts recommendations are using sound coding methodology; It is irresponsible of an expert to recommend bad coding habits.


[quote]
VB is not C++ and any comparison between the two and the coding necessary to achieve a desired aim is invidious.
[/quote]
VB and C++ are linked closer than you think. (in fact, they compile to the same intermediate object format, vb uses practically the same linker as VC (c2.exe), and many a time when coding complex applications I have gotten C++ error codes out of the VB IDE.

Comparing optimization techniques between vb and vc++ may not yield the results desired, comparing some implementation techniques (ie linked lists) may not be appropriate, but it is entirely possible and appropriate to compare *basic coding techniques* between C/C++ and Visual Basic.

The post was not invidious. It [was/is] about making sure that programmers who are inexperienced are getting sound advice on how to program.

From my own experience, and observation of many student programmers: Usage of Exit Sub leads to ambiguous code that is especially confusing for new programmers. It is akin to not declaring variables, and using End to close a program. They all make debugging much more difficult. That is all.

Since this is becoming highly off topic, please do email me if you wish to discuss this further: CyberKnet at Hotmail dot Com
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 4
  • 4
  • 2
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now