473,756 Members | 6,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about Try - Catch codes.

Hello, All!
I'm modifying some source code that I downloaded from
Planet-source-code a while back, and have a question about Try Catch
statements. Basically, I'm wondering if I can do a Try with multiple Catch
statements, or do I have to figure out how to embed Try Catch statements
into my code. The scenario is this (and I'll paste the actual code at the
bottom of this post). I'm modifying a web browser, and in the About Help
box, it has the "System Info" button. In the System Info button, there are
some GO TO statements that I want to get rid of. Plus, the SysInfoError
which is referred to by the GO TO statements doesn't tell you anything
except that an error happened.
What I'd like to do is put a Try at the beginning of the If-Then
statements, and for each possible error, put a Catch statement with a
message saying what the error is. I have a feeling, if I can't do that,
then a somewhat major rewrite of the subroutine is in order. Here's the
subroutine, and I appreciate any help that I can get. Also, If I end up
using snippets of code from here, I will definitely credit the poster.

Public Sub StartSysInfo()

On Error GoTo SysInfoErr
Dim rc As Integer

Dim SysInfoPath As String
' Try To Get System Info Program Path\Name From Registry...

If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
SysInfoPath) Then

' Try To Get System Info Program Path Only From Registry...

ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFOL OC, gREGVALSYSINFOL OC,
SysInfoPath) Then

' Validate Existance Of Known 32 Bit File Version

'UPGRADE_WARNIN G: Dir has a new behavior. Click for more:
'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?ke yword="vbup1041 "'

If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then

SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
' Error - File Can Not Be Found...

Else

GoTo SysInfoErr

End If

' Error - Registry Entry Can Not Be Found...

Else

GoTo SysInfoErr

End If
Call Shell(SysInfoPa th, AppWinStyle.Nor malFocus)
Exit Sub

SysInfoErr:

MsgBox("System Information Is Unavailable At This Time", MsgBoxStyle.OKO nly)

End Sub

Thank you again in advance.
With best regards, Patrick Dickey. E-mail: pd************* ********@msn.co m


---
avast! Antivirus: Outbound message clean.
Virus Database (VPS): 0521-3, 05/26/2005
Tested on: 5/27/2005 1:27:00 AM
avast! - copyright (c) 1988-2005 ALWIL Software.
http://www.avast.com

Nov 21 '05 #1
5 1764
Patrick Dickey wrote:
Basically, I'm wondering if I can do a Try with multiple
Catch statements


Yes you can. For example:

\\\
Try
[your code here]

Catch ex As OverflowExcepti on
[handle this type of error]

Catch ex As NullReferenceEx ception
[handle this type of error]

Catch ex As Exception
[handle all other error types]

End Try
///

--

(O) e n o n e
Nov 21 '05 #2
These two methods of error handling are completely different. The Try Catch
model relies upon exception handling, in other words when an exception is
thrown by a class or method, this can be seen inside the Try block and
caught by one or more Catch blocks. See example below.

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
Try

throwit1()

throwit2()

Catch ex As Exp1

MsgBox("1")

Catch ex As Exp2

MsgBox("2")

End Try

End Sub

Sub throwit1()

Throw New Exp1

End Sub

Sub throwit2()

Throw New Exp2

End Sub

If however you insist on using the OnError model, then you could OnErro Goto
YourErrorHandli ngCode: and use the Select Case Statement

Select Case YourErrorNumber
Case nn
Case nn
Case Else

End Case

This is a simplified answer, but it should put u in the right direction

HTH
--
Terry Burns
http://TrainingOn.net
"Patrick Dickey" <pd************ *********@msn.c om> wrote in message
news:Os******** ******@TK2MSFTN GP14.phx.gbl...
Hello, All!
I'm modifying some source code that I downloaded from
Planet-source-code a while back, and have a question about Try Catch
statements. Basically, I'm wondering if I can do a Try with multiple
Catch statements, or do I have to figure out how to embed Try Catch
statements into my code. The scenario is this (and I'll paste the actual
code at the bottom of this post). I'm modifying a web browser, and in the
About Help box, it has the "System Info" button. In the System Info
button, there are some GO TO statements that I want to get rid of. Plus,
the SysInfoError which is referred to by the GO TO statements doesn't tell
you anything except that an error happened.
What I'd like to do is put a Try at the beginning of the If-Then
statements, and for each possible error, put a Catch statement with a
message saying what the error is. I have a feeling, if I can't do that,
then a somewhat major rewrite of the subroutine is in order. Here's the
subroutine, and I appreciate any help that I can get. Also, If I end up
using snippets of code from here, I will definitely credit the poster.

Public Sub StartSysInfo()

On Error GoTo SysInfoErr
Dim rc As Integer

Dim SysInfoPath As String
' Try To Get System Info Program Path\Name From Registry...

If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
SysInfoPath) Then

' Try To Get System Info Program Path Only From Registry...

ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFOL OC,
gREGVALSYSINFOL OC, SysInfoPath) Then

' Validate Existance Of Known 32 Bit File Version

'UPGRADE_WARNIN G: Dir has a new behavior. Click for more:
'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?ke yword="vbup1041 "'

If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then

SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
' Error - File Can Not Be Found...

Else

GoTo SysInfoErr

End If

' Error - Registry Entry Can Not Be Found...

Else

GoTo SysInfoErr

End If
Call Shell(SysInfoPa th, AppWinStyle.Nor malFocus)
Exit Sub

SysInfoErr:

MsgBox("System Information Is Unavailable At This Time",
MsgBoxStyle.OKO nly)

End Sub

Thank you again in advance.
With best regards, Patrick Dickey. E-mail:
pd************* ********@msn.co m

---
avast! Antivirus: Outbound message clean.
Virus Database (VPS): 0521-3, 05/26/2005
Tested on: 5/27/2005 1:27:00 AM
avast! - copyright (c) 1988-2005 ALWIL Software.
http://www.avast.com

Nov 21 '05 #3
Hello, Patrick!
You wrote to All on Fri, 27 May 2005 01:26:58 -0500:

[Sorry, skipped to conserve space]

PD> Public Sub StartSysInfo()
PD>
PD> On Error GoTo SysInfoErr
PD>

PD> Dim rc As Integer
PD>
PD> Dim SysInfoPath As String
PD> ' Try To Get System Info Program Path\Name From Registry...
PD>
PD> If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
PD>
PD> SysInfoPath) Then
PD> ' Try To Get System Info Program Path Only From
PD> Registry...
PD> ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE ,
PD> gREGKEYSYSINFOL OC,
PD> gREGVALSYSINFOL OC,
PD> SysInfoPath) Then
PD> '
PD> Validate Existance Of Known 32 Bit File Version
PD> 'UPGRADE_WARNIN G: Dir
PD> has a new behavior. Click for more:
PD>
PD> 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?ke yword="
PD>
PD> vbup1041"'
PD> If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then
PD>
PD> SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
PD> ' Error - File Can Not Be
PD> Found...
PD> Else
PD> GoTo SysInfoErr
PD> End If
PD> ' Error - Registry
PD> Entry Can Not Be Found...
PD> Else
PD> GoTo SysInfoErr
PD> End If

PD> Call
PD> Shell(SysInfoPa th, AppWinStyle.Nor malFocus)
PD> Exit Sub
PD>
PD> SysInfoErr:
PD> MsgBox("System Information Is Unavailable At This
PD> Time",
PD> MsgBoxStyle.OKO nly)
PD> End Sub

[Sorry, skipped to conserve space]

Ok, I'm going to revamp this a little bit. For Terry's reply, I need to
clarify that I'm trying to eliminate all GOTO's-- Including the OnError Goto
statement. Bascially, I've ran a project analyzer on the code, and the
GOTO's are one thing it flagged. Plus, waaaaaaaaaaaaay back when I learned
programming (COBOL, Pascal, ApplesoftBASIC, FORTRAN, etc.) I was taught that
there is almost always a better way of coding then using GOTO. GOTO is
evil.. And, in most cases, the instructor would deduct points for GOTO
statements. Spaghetti programming, is the term we used for GOTO's.

So, here's what I'm thinking about doing. I'll recopy only the appropriate
IF-Then statements, and the end of the subroutine, and get everyone's
opinions. Thank you again, in advance.
Dim ErrorLevel as Integer
ErrorLevel = 0
If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
SysInfoPath) Then
' Try To Get System Info Program Path Only From Registry...
ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFOL OC,
gREGVALSYSINFOL OC, SysInfoPath) Then
' Validate Existance Of Known 32 Bit File Version
If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then
SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
Else
' Error - File Can Not Be Found...
ErrorLevel = 2
End If
Else
ErrorLevel = 1
' Error - Registry Entry Can Not Be Found...
End If

IF ErrorLevel = 1 Then
MsgBox("The Registry entry could not be found.", MsgBoxStyle.OKO nly)
ElseIF ErrorLevel = 2 Then
MsgBox("The Program File could not be found.", MsgBoxStyle.OKO nly)
Endif
EndIf

Basically, the only changes I want to make are creating an integer called
ErrorLevel, initializing it to 0 at the beginning, and then setting a value
for it, instead of using the "GOTO SysError" statements, in the IF-Then
statements.

With best regards, Patrick Dickey. E-mail: pd************* ********@msn.co m


---
avast! Antivirus: Outbound message clean.
Virus Database (VPS): 0522-1, 05/31/2005
Tested on: 5/31/2005 5:37:11 AM
avast! - copyright (c) 1988-2005 ALWIL Software.
http://www.avast.com

Nov 21 '05 #4
I would be more inclined to create an exception expecially for this and
throw it in your GetKeyValue calling function. Think about an approach which
looks something along these lines.

Try

GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO,
gREGVALSYSINFO, SysInfoPath) Then
GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFOL OC,gREGVALSYSIN FOLOC,
SysInfoPath) Then

If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then
SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
Else
Throw new FileNotFoundExc eption . . . . . . . . . stuff . . . . . .
End If

Catch ex as GetKeyValueExce ption

MsgBox ex.message ' or Some error handling code.

Catch ex as FileNotFoundExc eption

End Try

--
Terry Burns
http://TrainingOn.net
"Patrick Dickey" <pd************ *********@msn.c om> wrote in message
news:eb******** ******@TK2MSFTN GP15.phx.gbl...
Hello, Patrick!
You wrote to All on Fri, 27 May 2005 01:26:58 -0500:

[Sorry, skipped to conserve space]

PD> Public Sub StartSysInfo()
PD>
PD> On Error GoTo SysInfoErr
PD>

PD> Dim rc As Integer
PD>
PD> Dim SysInfoPath As String
PD> ' Try To Get System Info Program Path\Name From Registry...
PD>
PD> If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
PD>
PD> SysInfoPath) Then
PD> ' Try To Get System Info Program Path Only From
PD> Registry...
PD> ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE ,
PD> gREGKEYSYSINFOL OC,
PD> gREGVALSYSINFOL OC,
PD> SysInfoPath) Then
PD> '
PD> Validate Existance Of Known 32 Bit File Version
PD> 'UPGRADE_WARNIN G: Dir
PD> has a new behavior. Click for more:
PD>
PD> 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?ke yword="
PD>
PD> vbup1041"'
PD> If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then
PD>
PD> SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
PD> ' Error - File Can Not Be
PD> Found...
PD> Else
PD> GoTo SysInfoErr
PD> End If
PD> ' Error - Registry
PD> Entry Can Not Be Found...
PD> Else
PD> GoTo SysInfoErr
PD> End If

PD> Call
PD> Shell(SysInfoPa th, AppWinStyle.Nor malFocus)
PD> Exit Sub
PD>
PD> SysInfoErr:
PD> MsgBox("System Information Is Unavailable At This
PD> Time",
PD> MsgBoxStyle.OKO nly)
PD> End Sub

[Sorry, skipped to conserve space]

Ok, I'm going to revamp this a little bit. For Terry's reply, I need to
clarify that I'm trying to eliminate all GOTO's-- Including the OnError
Goto statement. Bascially, I've ran a project analyzer on the code, and
the GOTO's are one thing it flagged. Plus, waaaaaaaaaaaaay back when I
learned programming (COBOL, Pascal, ApplesoftBASIC, FORTRAN, etc.) I was
taught that there is almost always a better way of coding then using GOTO.
GOTO is evil.. And, in most cases, the instructor would deduct points for
GOTO statements. Spaghetti programming, is the term we used for GOTO's.

So, here's what I'm thinking about doing. I'll recopy only the
appropriate IF-Then statements, and the end of the subroutine, and get
everyone's opinions. Thank you again, in advance.
Dim ErrorLevel as Integer
ErrorLevel = 0
If GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFO, gREGVALSYSINFO,
SysInfoPath) Then
' Try To Get System Info Program Path Only From Registry...
ElseIf GetKeyValue(HKE Y_LOCAL_MACHINE , gREGKEYSYSINFOL OC,
gREGVALSYSINFOL OC, SysInfoPath) Then
' Validate Existance Of Known 32 Bit File Version
If (Dir(SysInfoPat h & "\MSINFO32.EXE" ) <> "") Then
SysInfoPath = SysInfoPath & "\MSINFO32. EXE"
Else
' Error - File Can Not Be Found...
ErrorLevel = 2
End If
Else
ErrorLevel = 1
' Error - Registry Entry Can Not Be Found...
End If

IF ErrorLevel = 1 Then
MsgBox("The Registry entry could not be found.", MsgBoxStyle.OKO nly)
ElseIF ErrorLevel = 2 Then
MsgBox("The Program File could not be found.", MsgBoxStyle.OKO nly)
Endif
EndIf

Basically, the only changes I want to make are creating an integer called
ErrorLevel, initializing it to 0 at the beginning, and then setting a
value for it, instead of using the "GOTO SysError" statements, in the
IF-Then statements.

With best regards, Patrick Dickey. E-mail:
pd************* ********@msn.co m

---
avast! Antivirus: Outbound message clean.
Virus Database (VPS): 0522-1, 05/31/2005
Tested on: 5/31/2005 5:37:11 AM
avast! - copyright (c) 1988-2005 ALWIL Software.
http://www.avast.com

Nov 21 '05 #5
"Patrick Dickey" <pd************ *********@msn.c om> wrote in message
news:Os******** ******@TK2MSFTN GP14.phx.gbl...
.. . .
Basically, I'm wondering if I can do a Try with multiple Catch
statements,


Yes you can, with one proviso - you have to "know" which
Exceptions derive from which other Exceptions and make sure
that you Catch the "smallest" one first, as in

Try
' Do Something database-y
Catch ox as System.Data.Odb c.OdbcException
Catch sx as System.SystemEx ception
Catch ex as System.Exceptio n
Finally
End Try

Each of these Exception classes is inherited from the next and, when
an Exception is thrown, the program will use the "most specific"
Exception Handler. If you were to put

Catch ex as System.Exceptio n

first, that's the /only/ handler that would ever get run.

HTH,
Phill W.
Nov 21 '05 #6

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

Similar topics

2
6381
by: fb | last post by:
Hi everyone. I have the following code. It was a question out of C++ how to program. I get a warning about "possible unreachable code" in the RunCode() function, but I don't see any problem with it... I was hoping for a better way of exiting the case statements below. I used exit() for "divide by zero" and "invalid instruction". I can't get a try/catch to work. Probably from a lack of experience. I have a fairly strong C...
9
1765
by: Dmitriy Lapshin [C# / .NET MVP] | last post by:
Hi all, When a good developer should declare an exception variable in a catch clause? Consider an example: try { // Do something potentially dangerous... } catch(SomeException e)
7
1389
by: Tiraman | last post by:
Hi , I am using allot the try catch in my code and the question is if it is good ? it will decrease my performance ? one more question
1
2632
by: Bruce | last post by:
Hi, there, I meet a problem about comboBox binding. -------------------- Database: Northwind Tables: 1) Products 2) Categories I create a form (named "form1") to edit the record from Products table.
14
1845
by: Mr Newbie | last post by:
I am often in the situation where I want to act on the result of a function, but a simple boolean is not enough. For example, I may have a function called isAuthorised ( User, Action ) as ????? OK, this function may return a boolean, and if this is true, then no message back is really required, but if it fails then some supporting message needs to be returned to the calling code. As I see it there are a few options.
1
2686
by: chen | last post by:
We're having an internal debate about the merits & demerits of returning status codes in the output message vs exceptions to signify errors in handling a Web method. The status code camp is arguing that business rules related errors are to be conveyed using status code while reserving the exception approach (using SoapException) to system related errors (like say database connection issues). This implies that GetFoo() returns a...
6
3140
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it to the client. Before adding data to the arraylist, I check if the depth of the arraylist is longer than iMaxQueueDepth, and if it is, I clear the arraylist. Is it possible that while I am clearing the arraylist, the ThreadMain at the same time...
20
3293
by: fniles | last post by:
I am using VS2003 and connecting to MS Access database. When using a connection pooling (every time I open the OLEDBCONNECTION I use the exact matching connection string), 1. how can I know how many connection has been used ? 2. If the maximum pool size has been reached, what happens when I call the method Open to open the connection ? Will I get an error ? MSDN says the request is queued, but will I get an error in the open method ? ...
4
1064
by: | last post by:
Hello Group I have a button click sub, which calles a function called 'send' to send over a tcp connection. This function can call an exception. If an exception occurs, I need to quit the button click function. My problem is how do I propagate the exception from the 'send' function, to the parent function (the button click function). Thanks (I have not done this sort of thing before) (unless the way it to simply use return codes and test...
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.