?
Solved

Error Handling Help !

Posted on 2003-03-21
16
Medium Priority
?
215 Views
Last Modified: 2010-04-07
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
Comment
Question by:ANGWK
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +5
16 Comments
 
LVL 13

Expert Comment

by:crazyman
ID: 8180162
place exit sub before

errhandler:


exit sub
errhandler:
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 8180208
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
 
LVL 1

Expert Comment

by:Piter
ID: 8180276

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
Independent Software Vendors: 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!

 

Author Comment

by:ANGWK
ID: 8180721
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
 
LVL 5

Expert Comment

by:TheMek
ID: 8180774
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
 

Author Comment

by:ANGWK
ID: 8180948
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
 
LVL 1

Accepted Solution

by:
cyberknet earned 80 total points
ID: 8181364
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
 

Author Comment

by:ANGWK
ID: 8181591
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
 

Expert Comment

by:charlob
ID: 8181619
cyberknet:

errhandler:
   Select Case Err.Number
       Case 0
       Case Else
           MsgBox "please insert floppy"
   End if    <---------------Sloppy coding??????? ;P
0
 
LVL 43

Expert Comment

by:TimCottee
ID: 8181774
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
 
LVL 5

Expert Comment

by:Cimperiali
ID: 8181897
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
 

Author Comment

by:ANGWK
ID: 8181994
well , indeed an expert :) yours really works !
0
 
LVL 5

Expert Comment

by:Cimperiali
ID: 8182060
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
 
LVL 5

Expert Comment

by:Cimperiali
ID: 8182078
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
 
LVL 5

Expert Comment

by:Cimperiali
ID: 8182509
Sorry, it was the author of "Hardcore Visual Basic" (Bruce McKinney)
0
 
LVL 1

Expert Comment

by:cyberknet
ID: 8182578
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Suggested Courses
Course of the Month13 days, 20 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question