473,398 Members | 2,389 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Try Catch Else Finally

cj
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else
statement. Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or
not, I haven't found a use for finally yet.

Mar 17 '06 #1
32 6067
That's what the Try is for. To do stuff with the assumption that there are
no errors. The catch is to deal with any errors. And the finally is to run
regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else statement.
Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or not,
I haven't found a use for finally yet.

Mar 17 '06 #2

Not too sure if I understand the question.

The mainline of the Try block is the implied 'do this if no error'
branch, with the the catch occuring only if an exception occurs.

Do you have an example of the functionality that you would like to see.
As for the finally

One example is to close files

e.g.

Dim fs As FileStream
Dim reader As TextReader

Try

fs = New FileStream("test.txt", FileMode.Open)
reader = New StreamReader(fs)

While True

Dim str As String = reader.ReadLine
If (str Is Nothing) Then
Exit While
End If

Trace.WriteLine(str)

End While

Finally

If Not fs Is Nothing Then
fs.Close()
End If

End Try

Say something went wrong during a read (or if we we doing something
more complicated with the input than just dumping it to trace) then
when we the exception occurs we want the filestream to be closed. We
also want it to be closed during the normal flow.
hth,
Alan

Mar 17 '06 #3
cj
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there are
no errors. The catch is to deal with any errors. And the finally is to run
regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else statement.
Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or not,
I haven't found a use for finally yet.


Mar 17 '06 #4
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch for
each line of code if you had different error handling code depending on
which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else
statement. Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or
not, I haven't found a use for finally yet.


Mar 17 '06 #5
cj
Your right Marina Levit has already set me straight. Only remaining
downside is I wouldn't know which line caused the exception. Thanks for
the reply.

AlanT wrote:
Not too sure if I understand the question.

The mainline of the Try block is the implied 'do this if no error'
branch, with the the catch occuring only if an exception occurs.

Do you have an example of the functionality that you would like to see.
As for the finally

One example is to close files

e.g.

Dim fs As FileStream
Dim reader As TextReader

Try

fs = New FileStream("test.txt", FileMode.Open)
reader = New StreamReader(fs)

While True

Dim str As String = reader.ReadLine
If (str Is Nothing) Then
Exit While
End If

Trace.WriteLine(str)

End While

Finally

If Not fs Is Nothing Then
fs.Close()
End If

End Try

Say something went wrong during a read (or if we we doing something
more complicated with the input than just dumping it to trace) then
when we the exception occurs we want the filestream to be closed. We
also want it to be closed during the normal flow.
hth,
Alan

Mar 17 '06 #6
cj
Thanks, I really didn't know or at least think about doing it that way.
I knew several lines could be in try but I guess I was still thinking
I needed to check soon to see if a particular line had an exception. I
guess I still do but I guess I can have nested try blocks. That'd
probably take care of my issues. Thanks!

Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch for
each line of code if you had different error handling code depending on
which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else
statement. Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or
not, I haven't found a use for finally yet.

Mar 17 '06 #7
cj
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub
should only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch for
each line of code if you had different error handling code depending on
which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
Another wish of mine. I wish there was a way in the Try Catch structure
to say if there wasn't an error to do something. Like an else
statement. Try Catch Else Finally.

Also because I understand Finally runs whether an error was caught or
not, I haven't found a use for finally yet.

Mar 17 '06 #8
I don't really follow what you are saying here.

I would re-evaluate if you really need different error handling logic for
every statement. Nested try/catch blocks look pretty ugly and are hard to
follow.

The finally statements are different because they execute after the Try if
no errors happened. They also execute if there was an error and a catch was
run. The Finally block is guaranteed to execute regardless of whether or not
an error occurred in the Try.

I recommend you read up on try/catch/finally blocks in the documentation and
take a look at some samples. That might help you figure out the right way of
using it.

"cj" <cj@nospam.nospam> wrote in message
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub should
only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch
for each line of code if you had different error handling code depending
on which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
> Another wish of mine. I wish there was a way in the Try Catch
> structure to say if there wasn't an error to do something. Like an
> else statement. Try Catch Else Finally.
>
> Also because I understand Finally runs whether an error was caught or
> not, I haven't found a use for finally yet.
>

Mar 17 '06 #9
> Your right Marina Levit has already set me straight. Only remaining
downside is I wouldn't know which line caused the exception. Thanks
for the reply.


You CAN get the line that caused the exception if you number your lines (like
old Basic). The following is perfectly acceptable VB.Net code:

10: REM This program doesn't do much
20: Try
30: REM Throw an error
40: Throw New DivideByZeroException
50: Catch ex As DivideByZeroException
60: Console.WriteLine("Error occured in line: " & Erl())
70: End Try
80: Console.ReadLine()

The output is:

Error occured in line: 40

The upside is: the line numbers are retained when you compile in release
mode. The down side is that there is a performance hit, so you would only
want to do this when it is essential you know the line causing the problem
and speed is not as important.

Jim Wooley
http://devauthority.com/blogs/jwoole...12/21/661.aspx
Mar 17 '06 #10

The stack trace from the exception will show you where the exception
occurred.

hth,
Alan.

Mar 17 '06 #11
CJ,

The statements in the finally block will be always executed unless you power
your computer down before that or execute the End statement. (Even if there
is a return in the sub than the finally will be done first).

I hope this helps,

Cor

"cj" <cj@nospam.nospam> schreef in bericht
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub should
only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch
for each line of code if you had different error handling code depending
on which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.

"cj" <cj@nospam.nospam> wrote in message
news:uO**************@TK2MSFTNGP14.phx.gbl...
> Another wish of mine. I wish there was a way in the Try Catch
> structure to say if there wasn't an error to do something. Like an
> else statement. Try Catch Else Finally.
>
> Also because I understand Finally runs whether an error was caught or
> not, I haven't found a use for finally yet.
>

Mar 17 '06 #12
cj
My cut and paste typing was pretty bad wasn't it. Let me try again.

I have this now. The IF that checks to see if I got back session
dropped should not execute if respstr=proxy.validate failed. Here I
ensure that by checking to see if respstr=""

Try
respstr = proxy.validate(soapmesg)
Catch ex As Exception
procLabel2.Text = Now() & " Error executing Validation request"
procLabel3.Text = ex.Message
respstr = ""
End Try

If Not respstr = "" And respstr.Substring(0, 28) = _
"Session Dropped, Login Again" Then
loginABC(Me, Nothing)
End If

Suppose I did this instead:

Try
respstr = proxy.validate(soapmesg)
If respstr.Substring(0, 28) = "Session Dropped, Login Again" Then
loginABC(Me, Nothing)
End If
Catch ex As Exception
procLabel2.Text = Now() & " Error executing Validation request"
procLabel3.Text = ex.Message
End Try

Is it possible the catch would catch and error that occured in loginABC?
I hope not.

Marina Levit [MVP] wrote:
I don't really follow what you are saying here.

I would re-evaluate if you really need different error handling logic for
every statement. Nested try/catch blocks look pretty ugly and are hard to
follow.

The finally statements are different because they execute after the Try if
no errors happened. They also execute if there was an error and a catch was
run. The Finally block is guaranteed to execute regardless of whether or not
an error occurred in the Try.

I recommend you read up on try/catch/finally blocks in the documentation and
take a look at some samples. That might help you figure out the right way of
using it.

"cj" <cj@nospam.nospam> wrote in message
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub should
only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch
for each line of code if you had different error handling code depending
on which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
> That's what the Try is for. To do stuff with the assumption that there
> are no errors. The catch is to deal with any errors. And the finally is
> to run regardless of whether or not there were errors.
>
> "cj" <cj@nospam.nospam> wrote in message
> news:uO**************@TK2MSFTNGP14.phx.gbl...
>> Another wish of mine. I wish there was a way in the Try Catch
>> structure to say if there wasn't an error to do something. Like an
>> else statement. Try Catch Else Finally.
>>
>> Also because I understand Finally runs whether an error was caught or
>> not, I haven't found a use for finally yet.
>>


Mar 17 '06 #13
Hi,

Is there something I'm missing here, Jim ? Why go to such an extent
when the line no. can be determined easily. If I simply include the
following line within my Catch block :

:
:
Catch ex as Exception
Console.WriteLine("ex.ToString()")
Finally...
I can get the output which gives the Line no. at which the error
occurred. This is because using ToString() here appends the Message
Property and the StackTrace property (which contains the Line no.) and
displays it as a string.

So, why should we have to add in Line nos. manually to the code ?

Regards,

Cerebrus.

Mar 17 '06 #14
cj
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in using
try catch is that without it, or some other error handling, if a command
throws an exception the program halts with some garbage on the screen.
I've written my program with try catch around statements like calls to
other servers where something like a cable being cut might cause the
line to throw and exception as it can not execute. In the catch I want
to know what command is giving the problem. That'll help me know what
is wrong. I print a custom message to indicate what code is being
executed and the ex.message info to the screen for diagnosis. I need to
know which stored procedure will not work, or is it the request to the
remote server or did it try to parse the xml file and find out it wasn't
a xml file? The presence of an error like this can mean skip the
current record or it might mean reattempt the failed command until it
starts working.

In any event after the try catch the program continues to run. I test a
flag variable or some other way to see if the previous statement threw
an exception and make my processing decisions based on that. So my code
after the try catch always executes--how is that different from being in
finally?

Cor Ligthert [MVP] wrote:
CJ,

The statements in the finally block will be always executed unless you power
your computer down before that or execute the End statement. (Even if there
is a return in the sub than the finally will be done first).

I hope this helps,

Cor

"cj" <cj@nospam.nospam> schreef in bericht
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub should
only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate try/catch
for each line of code if you had different error handling code depending
on which exact one threw the exception.
Or if the different things threw different types of exceptions, you could
have multiple catch blocks each catching a different exception type, and
have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
So are you saying if I have that if line 2 throws and exception it will
skip 3, 4 and 5 and go straight to catch?

If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
> That's what the Try is for. To do stuff with the assumption that there
> are no errors. The catch is to deal with any errors. And the finally is
> to run regardless of whether or not there were errors.
>
> "cj" <cj@nospam.nospam> wrote in message
> news:uO**************@TK2MSFTNGP14.phx.gbl...
>> Another wish of mine. I wish there was a way in the Try Catch
>> structure to say if there wasn't an error to do something. Like an
>> else statement. Try Catch Else Finally.
>>
>> Also because I understand Finally runs whether an error was caught or
>> not, I haven't found a use for finally yet.
>>


Mar 17 '06 #15
cj
My guess would be he assumes, and I expect I would if I used this
approach, make a decision on what to do in the catch based on the line
number catch tells me the error occurred on. So I need at coding time
to see what line is what number to program in specific actions to be
taken for specific lines.

Sorry Jim, line numbers are on thing I don't want to bring back.
Cerebrus wrote:
Hi,

Is there something I'm missing here, Jim ? Why go to such an extent
when the line no. can be determined easily. If I simply include the
following line within my Catch block :

:
:
Catch ex as Exception
Console.WriteLine("ex.ToString()")
Finally...
I can get the output which gives the Line no. at which the error
occurred. This is because using ToString() here appends the Message
Property and the StackTrace property (which contains the Line no.) and
displays it as a string.

So, why should we have to add in Line nos. manually to the code ?

Regards,

Cerebrus.

Mar 17 '06 #16
Hi CJ

Here is an example

<code>
Sub Button1_Click(...) Handles ...

Try
DoFileStuff

Catch ex As Exception
' This is a catch-all because we don't want
' our button click handler to blow up
MessageBox.Show(ex.Message)

End Try

End Sub

Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Finally
' This will always execute, even if UnexpectedException is thrown
If FileIsOpen Then
CloseFile
End If

End Try

' Code here will not execute if UnexpectedException is thrown,
' so we cannot rely on closing the file here

End Sub
</code>

HTH

Charles
"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
I guess I'll have to do some reading on finally. I'm still not sure I see
the use. Perhaps it's how I'm using try catch. My purpose in using try
catch is that without it, or some other error handling, if a command throws
an exception the program halts with some garbage on the screen. I've
written my program with try catch around statements like calls to other
servers where something like a cable being cut might cause the line to
throw and exception as it can not execute. In the catch I want to know
what command is giving the problem. That'll help me know what is wrong. I
print a custom message to indicate what code is being executed and the
ex.message info to the screen for diagnosis. I need to know which stored
procedure will not work, or is it the request to the remote server or did
it try to parse the xml file and find out it wasn't a xml file? The
presence of an error like this can mean skip the current record or it might
mean reattempt the failed command until it starts working.

In any event after the try catch the program continues to run. I test a
flag variable or some other way to see if the previous statement threw an
exception and make my processing decisions based on that. So my code
after the try catch always executes--how is that different from being in
finally?

Cor Ligthert [MVP] wrote:
CJ,

The statements in the finally block will be always executed unless you
power your computer down before that or execute the End statement. (Even
if there is a return in the sub than the finally will be done first).

I hope this helps,

Cor

"cj" <cj@nospam.nospam> schreef in bericht
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub
should only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
Yes, that is what I am saying. That is the whole point of a try block.

You wouldn't know which one it was. You would need a separate
try/catch for each line of code if you had different error handling
code depending on which exact one threw the exception.
Or if the different things threw different types of exceptions, you
could have multiple catch blocks each catching a different exception
type, and have different error handling code execute that way.

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
> So are you saying if I have that if line 2 throws and exception it
> will skip 3, 4 and 5 and go straight to catch?
>
> If so, the next question is how do I know it was line 2 that threw the
> exception and not line 1 or 4?
>
> try
> 1
> 2
> 3
> 4
> 5
> catch
> a
> end try
>
> Marina Levit [MVP] wrote:
>> That's what the Try is for. To do stuff with the assumption that
>> there are no errors. The catch is to deal with any errors. And the
>> finally is to run regardless of whether or not there were errors.
>>
>> "cj" <cj@nospam.nospam> wrote in message
>> news:uO**************@TK2MSFTNGP14.phx.gbl...
>>> Another wish of mine. I wish there was a way in the Try Catch
>>> structure to say if there wasn't an error to do something. Like an
>>> else statement. Try Catch Else Finally.
>>>
>>> Also because I understand Finally runs whether an error was caught
>>> or not, I haven't found a use for finally yet.
>>>


Mar 17 '06 #17
It could be also because he tries to catch global errors instead of having
multiple catch clauses. IMO he's best bet for now would be to give a close
look at the Try statement...
--
Patrice

"cj" <cj@nospam.nospam> a écrit dans le message de news:
uU*************@TK2MSFTNGP12.phx.gbl...
My guess would be he assumes, and I expect I would if I used this
approach, make a decision on what to do in the catch based on the line
number catch tells me the error occurred on. So I need at coding time to
see what line is what number to program in specific actions to be taken
for specific lines.

Sorry Jim, line numbers are on thing I don't want to bring back.
Cerebrus wrote:
Hi,

Is there something I'm missing here, Jim ? Why go to such an extent
when the line no. can be determined easily. If I simply include the
following line within my Catch block :

:
:
Catch ex as Exception
Console.WriteLine("ex.ToString()")
Finally...
I can get the output which gives the Line no. at which the error
occurred. This is because using ToString() here appends the Message
Property and the StackTrace property (which contains the Line no.) and
displays it as a string.

So, why should we have to add in Line nos. manually to the code ?

Regards,

Cerebrus.

Mar 17 '06 #18
You can get line numbers, but that is only good for showing error messages.
It's not like you can in code figure out which function call caused the
error - unless you start hard coding if statements to look for specific line
numbers - but that isn't something you would ever want to do.

cj wanted to figure out which line of code was causing the problem, to
presumably either have different error handling code, or ignore the error,
etc. That isn't something the stack trace information can realistically help
with.

Not to mention, line numbers come up only when compiled in debug mode.

"Jim Wooley" <ji*************@hotmail.com> wrote in message
news:24*************************@msnews.microsoft. com...
Your right Marina Levit has already set me straight. Only remaining
downside is I wouldn't know which line caused the exception. Thanks
for the reply.


You CAN get the line that caused the exception if you number your lines
(like old Basic). The following is perfectly acceptable VB.Net code:

10: REM This program doesn't do much
20: Try
30: REM Throw an error
40: Throw New DivideByZeroException
50: Catch ex As DivideByZeroException
60: Console.WriteLine("Error occured in line: " & Erl())
70: End Try
80: Console.ReadLine()

The output is:

Error occured in line: 40

The upside is: the line numbers are retained when you compile in release
mode. The down side is that there is a performance hit, so you would only
want to do this when it is essential you know the line causing the problem
and speed is not as important.

Jim Wooley
http://devauthority.com/blogs/jwoole...12/21/661.aspx

Mar 17 '06 #19
cj
I see a couple things here.

1. is the button1_click catch catching exceptions thrown by lines
inside dofilestuff or just if the line dofilestuff itself for some
reason threw an exception?

2. your catching different types of exceptions. I'm catching any
exceptions and treating them all the same. The show must go on in my
program regardless of any exceptions. Some lines an exception on them
would be best handled by retrying the line and others by skipping to the
next iteration of the program. ie on reading from a server it'd be best
to retry untill it works while on getting a badly formated xml file from
the server I'd probably flag that transaction as questionable and try
the next request.
Charles Law wrote:
Hi CJ

Here is an example

<code>
Sub Button1_Click(...) Handles ...

Try
DoFileStuff

Catch ex As Exception
' This is a catch-all because we don't want
' our button click handler to blow up
MessageBox.Show(ex.Message)

End Try

End Sub

Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Finally
' This will always execute, even if UnexpectedException is thrown
If FileIsOpen Then
CloseFile
End If

End Try

' Code here will not execute if UnexpectedException is thrown,
' so we cannot rely on closing the file here

End Sub
</code>

HTH

Charles
"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
I guess I'll have to do some reading on finally. I'm still not sure I see
the use. Perhaps it's how I'm using try catch. My purpose in using try
catch is that without it, or some other error handling, if a command throws
an exception the program halts with some garbage on the screen. I've
written my program with try catch around statements like calls to other
servers where something like a cable being cut might cause the line to
throw and exception as it can not execute. In the catch I want to know
what command is giving the problem. That'll help me know what is wrong. I
print a custom message to indicate what code is being executed and the
ex.message info to the screen for diagnosis. I need to know which stored
procedure will not work, or is it the request to the remote server or did
it try to parse the xml file and find out it wasn't a xml file? The
presence of an error like this can mean skip the current record or it might
mean reattempt the failed command until it starts working.

In any event after the try catch the program continues to run. I test a
flag variable or some other way to see if the previous statement threw an
exception and make my processing decisions based on that. So my code
after the try catch always executes--how is that different from being in
finally?

Cor Ligthert [MVP] wrote:
CJ,

The statements in the finally block will be always executed unless you
power your computer down before that or execute the End statement. (Even
if there is a return in the sub than the finally will be done first).

I hope this helps,

Cor

"cj" <cj@nospam.nospam> schreef in bericht
news:O%****************@TK2MSFTNGP14.phx.gbl...
If I call a sub as one of the inside within a try, would the try trap
errors in the sub? I hope not. My intention is only that this sub
should only be run if there were no errors in the statement before it.

Also I'm not sure I understand Finally. How are statements in finally
different from those that follow the end try?
Marina Levit [MVP] wrote:
> Yes, that is what I am saying. That is the whole point of a try block.
>
> You wouldn't know which one it was. You would need a separate
> try/catch for each line of code if you had different error handling
> code depending on which exact one threw the exception.
> Or if the different things threw different types of exceptions, you
> could have multiple catch blocks each catching a different exception
> type, and have different error handling code execute that way.
>
> "cj" <cj@nospam.nospam> wrote in message
> news:%2****************@TK2MSFTNGP14.phx.gbl...
>> So are you saying if I have that if line 2 throws and exception it
>> will skip 3, 4 and 5 and go straight to catch?
>>
>> If so, the next question is how do I know it was line 2 that threw the
>> exception and not line 1 or 4?
>>
>> try
>> 1
>> 2
>> 3
>> 4
>> 5
>> catch
>> a
>> end try
>>
>> Marina Levit [MVP] wrote:
>>> That's what the Try is for. To do stuff with the assumption that
>>> there are no errors. The catch is to deal with any errors. And the
>>> finally is to run regardless of whether or not there were errors.
>>>
>>> "cj" <cj@nospam.nospam> wrote in message
>>> news:uO**************@TK2MSFTNGP14.phx.gbl...
>>>> Another wish of mine. I wish there was a way in the Try Catch
>>>> structure to say if there wasn't an error to do something. Like an
>>>> else statement. Try Catch Else Finally.
>>>>
>>>> Also because I understand Finally runs whether an error was caught
>>>> or not, I haven't found a use for finally yet.
>>>>

Mar 17 '06 #20
Hi Cj
1. is the button1_click catch catching exceptions thrown by lines inside
dofilestuff or just if the line dofilestuff itself for some reason threw
an exception?
The Catch in Button1_Click() catches any exception that 'escapes' from
DoFileStuff(). So, if UnexpectedException is thrown it will be caught in
Button1_Click(). If SomeException is thrown it will be caught in
DoFileStuff(). If DoFileStuff() rethrows it, or throws it as some other
exception, then that will be caught in Button1_Click(). Otherwise,
DoFileStuff() can consume the exception and retry the offending code or move
on to the next iteration, if that is what is happening (the logic in
DoFileStuff() would have to support this).
2. your catching different types of exceptions. I'm catching any
exceptions and treating them all the same. The show must go on in my
program regardless of any exceptions. Some lines an exception on them
would be best handled by retrying the line and others by skipping to the
next iteration of the program. ie on reading from a server it'd be best
to retry untill it works while on getting a badly formated xml file from
the server I'd probably flag that transaction as questionable and try the
next request.
I wasn't trying to be prescriptive about how your exception handling should
be done. I was just trying to give an example of how Finally is useful.
However, there does seem to be a case for catching some exceptions
separately, and then having a catch-all to cover unexpected exceptions. You
could have

<code>
Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Catch ex As Exception
' Catch all other exceptions and perform some
' default action and try to keep going

Finally
If FileIsOpen Then
CloseFile
End If

End Try

End Sub
</code>

Charles

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...I see a couple things here.

1. is the button1_click catch catching exceptions thrown by lines inside
dofilestuff or just if the line dofilestuff itself for some reason threw
an exception?

2. your catching different types of exceptions. I'm catching any
exceptions and treating them all the same. The show must go on in my
program regardless of any exceptions. Some lines an exception on them
would be best handled by retrying the line and others by skipping to the
next iteration of the program. ie on reading from a server it'd be best
to retry untill it works while on getting a badly formated xml file from
the server I'd probably flag that transaction as questionable and try the
next request.
Charles Law wrote:
Hi CJ

Here is an example

<code>
Sub Button1_Click(...) Handles ...

Try
DoFileStuff

Catch ex As Exception
' This is a catch-all because we don't want
' our button click handler to blow up
MessageBox.Show(ex.Message)

End Try

End Sub

Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Finally
' This will always execute, even if UnexpectedException is thrown
If FileIsOpen Then
CloseFile
End If

End Try

' Code here will not execute if UnexpectedException is thrown,
' so we cannot rely on closing the file here

End Sub
</code>

HTH

Charles
"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in using
try catch is that without it, or some other error handling, if a command
throws an exception the program halts with some garbage on the screen.
I've written my program with try catch around statements like calls to
other servers where something like a cable being cut might cause the
line to throw and exception as it can not execute. In the catch I want
to know what command is giving the problem. That'll help me know what
is wrong. I print a custom message to indicate what code is being
executed and the ex.message info to the screen for diagnosis. I need to
know which stored procedure will not work, or is it the request to the
remote server or did it try to parse the xml file and find out it wasn't
a xml file? The presence of an error like this can mean skip the
current record or it might mean reattempt the failed command until it
starts working.

In any event after the try catch the program continues to run. I test a
flag variable or some other way to see if the previous statement threw
an exception and make my processing decisions based on that. So my code
after the try catch always executes--how is that different from being in
finally?

Cor Ligthert [MVP] wrote:
CJ,

The statements in the finally block will be always executed unless you
power your computer down before that or execute the End statement.
(Even if there is a return in the sub than the finally will be done
first).

I hope this helps,

Cor

"cj" <cj@nospam.nospam> schreef in bericht
news:O%****************@TK2MSFTNGP14.phx.gbl...
> If I call a sub as one of the inside within a try, would the try trap
> errors in the sub? I hope not. My intention is only that this sub
> should only be run if there were no errors in the statement before it.
>
> Also I'm not sure I understand Finally. How are statements in finally
> different from those that follow the end try?
>
>
> Marina Levit [MVP] wrote:
>> Yes, that is what I am saying. That is the whole point of a try
>> block.
>>
>> You wouldn't know which one it was. You would need a separate
>> try/catch for each line of code if you had different error handling
>> code depending on which exact one threw the exception.
>> Or if the different things threw different types of exceptions, you
>> could have multiple catch blocks each catching a different exception
>> type, and have different error handling code execute that way.
>>
>> "cj" <cj@nospam.nospam> wrote in message
>> news:%2****************@TK2MSFTNGP14.phx.gbl...
>>> So are you saying if I have that if line 2 throws and exception it
>>> will skip 3, 4 and 5 and go straight to catch?
>>>
>>> If so, the next question is how do I know it was line 2 that threw
>>> the exception and not line 1 or 4?
>>>
>>> try
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> catch
>>> a
>>> end try
>>>
>>> Marina Levit [MVP] wrote:
>>>> That's what the Try is for. To do stuff with the assumption that
>>>> there are no errors. The catch is to deal with any errors. And the
>>>> finally is to run regardless of whether or not there were errors.
>>>>
>>>> "cj" <cj@nospam.nospam> wrote in message
>>>> news:uO**************@TK2MSFTNGP14.phx.gbl...
>>>>> Another wish of mine. I wish there was a way in the Try Catch
>>>>> structure to say if there wasn't an error to do something. Like
>>>>> an else statement. Try Catch Else Finally.
>>>>>
>>>>> Also because I understand Finally runs whether an error was caught
>>>>> or not, I haven't found a use for finally yet.
>>>>>

Mar 17 '06 #21
> You can get line numbers, but that is only good for showing error
messages. It's not like you can in code figure out which function call
caused the error - unless you start hard coding if statements to look
for specific line numbers - but that isn't something you would ever
want to do.

cj wanted to figure out which line of code was causing the problem, to
presumably either have different error handling code, or ignore the
error, etc. That isn't something the stack trace information can
realistically help with.
I think we can agree that using the old On Error GOTO...Resume Next method
is far from ideal. Structured exception handling is a better, more robust
mechanism and would be the prefered method. I am not advocating using the
line numbers and ERL(), more-so mentioning that it is possible.
Not to mention, line numbers come up only when compiled in debug mode.


ERR. Sorry. Thanks for playing. I just tested it in VS2005 and the line number
is retained in a release mode when hard coded as in my sample. You do not
get the line numbers in the stack trace, but ERL() will still report the
line number if it is included in the source code. Hence the additional overhead.
I just checked the sample code with Reflector and the VB compiler is adding
a variable to track the line numbers and incrementing it interspersed in
the code, similar to inserting a trace.write method in the body of the code.
Here's the dis-assembled version of the previous sample:

Public Shared Sub Main()
Dim num1 As Integer = 10
num1 = 20
Try
num1 = 30
num1 = 40
Throw New DivideByZeroException
Catch exception2 As DivideByZeroException
ProjectData.SetProjectError(exception2, num1)
Dim exception1 As DivideByZeroException = exception2
num1 = 60
Console.WriteLine(("Error occured in line: " & Conversions.ToString(Information.Erl)))
num1 = 70
ProjectData.ClearProjectError
End Try
num1 = 80
Console.ReadLine

As you can see, it works but is far from elegant and the performance implications
are not good.
Mar 17 '06 #22
> Hi,

Is there something I'm missing here, Jim ? Why go to such an extent
when the line no. can be determined easily.


The difference is the release build vs the debug build. The line numbers
are stripped from the stack trace in a release build. I didn't mean to say
that you should use them, just that you could.

Jim Wooley
(new post: http://devauthority.com/blogs/jwoole...03/17/795.aspx)
Mar 17 '06 #23
cj
Thanks.

Charles Law wrote:
Hi Cj
1. is the button1_click catch catching exceptions thrown by lines inside
dofilestuff or just if the line dofilestuff itself for some reason threw
an exception?


The Catch in Button1_Click() catches any exception that 'escapes' from
DoFileStuff(). So, if UnexpectedException is thrown it will be caught in
Button1_Click(). If SomeException is thrown it will be caught in
DoFileStuff(). If DoFileStuff() rethrows it, or throws it as some other
exception, then that will be caught in Button1_Click(). Otherwise,
DoFileStuff() can consume the exception and retry the offending code or move
on to the next iteration, if that is what is happening (the logic in
DoFileStuff() would have to support this).
2. your catching different types of exceptions. I'm catching any
exceptions and treating them all the same. The show must go on in my
program regardless of any exceptions. Some lines an exception on them
would be best handled by retrying the line and others by skipping to the
next iteration of the program. ie on reading from a server it'd be best
to retry untill it works while on getting a badly formated xml file from
the server I'd probably flag that transaction as questionable and try the
next request.


I wasn't trying to be prescriptive about how your exception handling should
be done. I was just trying to give an example of how Finally is useful.
However, there does seem to be a case for catching some exceptions
separately, and then having a catch-all to cover unexpected exceptions. You
could have

<code>
Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Catch ex As Exception
' Catch all other exceptions and perform some
' default action and try to keep going

Finally
If FileIsOpen Then
CloseFile
End If

End Try

End Sub
</code>

Charles

"cj" <cj@nospam.nospam> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I see a couple things here.

1. is the button1_click catch catching exceptions thrown by lines inside
dofilestuff or just if the line dofilestuff itself for some reason threw
an exception?

2. your catching different types of exceptions. I'm catching any
exceptions and treating them all the same. The show must go on in my
program regardless of any exceptions. Some lines an exception on them
would be best handled by retrying the line and others by skipping to the
next iteration of the program. ie on reading from a server it'd be best
to retry untill it works while on getting a badly formated xml file from
the server I'd probably flag that transaction as questionable and try the
next request.
Charles Law wrote:
Hi CJ

Here is an example

<code>
Sub Button1_Click(...) Handles ...

Try
DoFileStuff

Catch ex As Exception
' This is a catch-all because we don't want
' our button click handler to blow up
MessageBox.Show(ex.Message)

End Try

End Sub

Sub DoFileStuff()

Try
OpenFile

WriteToFile

Catch ex As SpecificException
' Catch this exception because we know what to do if it occurs

Catch ex As SomeOtherExceptionThatICanHandle
' Catch this exception as well for the same reason. However
' it requires a different reaction, so we catch it separately

Finally
' This will always execute, even if UnexpectedException is thrown
If FileIsOpen Then
CloseFile
End If

End Try

' Code here will not execute if UnexpectedException is thrown,
' so we cannot rely on closing the file here

End Sub
</code>

HTH

Charles
"cj" <cj@nospam.nospam> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in using
try catch is that without it, or some other error handling, if a command
throws an exception the program halts with some garbage on the screen.
I've written my program with try catch around statements like calls to
other servers where something like a cable being cut might cause the
line to throw and exception as it can not execute. In the catch I want
to know what command is giving the problem. That'll help me know what
is wrong. I print a custom message to indicate what code is being
executed and the ex.message info to the screen for diagnosis. I need to
know which stored procedure will not work, or is it the request to the
remote server or did it try to parse the xml file and find out it wasn't
a xml file? The presence of an error like this can mean skip the
current record or it might mean reattempt the failed command until it
starts working.

In any event after the try catch the program continues to run. I test a
flag variable or some other way to see if the previous statement threw
an exception and make my processing decisions based on that. So my code
after the try catch always executes--how is that different from being in
finally?

Cor Ligthert [MVP] wrote:
> CJ,
>
> The statements in the finally block will be always executed unless you
> power your computer down before that or execute the End statement.
> (Even if there is a return in the sub than the finally will be done
> first).
>
> I hope this helps,
>
> Cor
>
> "cj" <cj@nospam.nospam> schreef in bericht
> news:O%****************@TK2MSFTNGP14.phx.gbl...
>> If I call a sub as one of the inside within a try, would the try trap
>> errors in the sub? I hope not. My intention is only that this sub
>> should only be run if there were no errors in the statement before it.
>>
>> Also I'm not sure I understand Finally. How are statements in finally
>> different from those that follow the end try?
>>
>>
>> Marina Levit [MVP] wrote:
>>> Yes, that is what I am saying. That is the whole point of a try
>>> block.
>>>
>>> You wouldn't know which one it was. You would need a separate
>>> try/catch for each line of code if you had different error handling
>>> code depending on which exact one threw the exception.
>>> Or if the different things threw different types of exceptions, you
>>> could have multiple catch blocks each catching a different exception
>>> type, and have different error handling code execute that way.
>>>
>>> "cj" <cj@nospam.nospam> wrote in message
>>> news:%2****************@TK2MSFTNGP14.phx.gbl...
>>>> So are you saying if I have that if line 2 throws and exception it
>>>> will skip 3, 4 and 5 and go straight to catch?
>>>>
>>>> If so, the next question is how do I know it was line 2 that threw
>>>> the exception and not line 1 or 4?
>>>>
>>>> try
>>>> 1
>>>> 2
>>>> 3
>>>> 4
>>>> 5
>>>> catch
>>>> a
>>>> end try
>>>>
>>>> Marina Levit [MVP] wrote:
>>>>> That's what the Try is for. To do stuff with the assumption that
>>>>> there are no errors. The catch is to deal with any errors. And the
>>>>> finally is to run regardless of whether or not there were errors.
>>>>>
>>>>> "cj" <cj@nospam.nospam> wrote in message
>>>>> news:uO**************@TK2MSFTNGP14.phx.gbl...
>>>>>> Another wish of mine. I wish there was a way in the Try Catch
>>>>>> structure to say if there wasn't an error to do something. Like
>>>>>> an else statement. Try Catch Else Finally.
>>>>>>
>>>>>> Also because I understand Finally runs whether an error was caught
>>>>>> or not, I haven't found a use for finally yet.
>>>>>>


Mar 17 '06 #24
> I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in
using try catch is that without it, or some other error handling, if a
command throws an exception the program halts with some garbage on the
screen. I've written my program with try catch around statements like
calls to other servers where something like a cable being cut might
cause the line to throw and exception as it can not execute. In the
catch I want to know what command is giving the problem. That'll help
me know what is wrong. I print a custom message to indicate what code
is being executed and the ex.message info to the screen for diagnosis.
I need to know which stored procedure will not work, or is it the
request to the remote server or did it try to parse the xml file and
find out it wasn't a xml file? The presence of an error like this can
mean skip the current record or it might mean reattempt the failed
command until it starts working.


As COR indicated, the finally block should be used to close resources and
do other necessary cleanup to get your program back to a valid state. You
would want to make sure to clean the resources regardless of whether a exception
is thrown. Consider the following pseudocode:

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
end try

cn.dispose
cn.close

In this case, the connection (an expensive resource) is left open if the
exception is thrown. As an alternative, you can do the following

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
finally
cn.close
cn.dispose
end try

In this case, we are assured that the connection will be closed. Starting
with VB2005, we can change this as follows:

Using cn as new Connection
try
cn.open
catch
messagebox.show("Problem with connection")
end try
end using

Now we are assured that the connection is properly handled as the Using block
handles the dispose for us and closes the connection. Now, if we want to
simply let the exception bubble up to a calling method, we can trim this
down to:

Using cn as new Connection
cn.open
end using

An exception will still be thrown, but the resource will be released correctly.

Jim Wooley
http://devauthority.com/blogs/jwooley
Mar 17 '06 #25
cj
Give me an example of an exception that could be thrown that still
allowed the db connection to open. Honestly, I'd like to know. I'm
sure there are some but it seems to me the most likely reason that line
would throw and exception is it couldn't open the db.

second, assume it didn't open the db and then you fall to the finally
section and you try to close a db that isn't open. wouldn't this also
throw and exception?
Jim Wooley wrote:
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in
using try catch is that without it, or some other error handling, if a
command throws an exception the program halts with some garbage on the
screen. I've written my program with try catch around statements like
calls to other servers where something like a cable being cut might
cause the line to throw and exception as it can not execute. In the
catch I want to know what command is giving the problem. That'll help
me know what is wrong. I print a custom message to indicate what code
is being executed and the ex.message info to the screen for diagnosis.
I need to know which stored procedure will not work, or is it the
request to the remote server or did it try to parse the xml file and
find out it wasn't a xml file? The presence of an error like this can
mean skip the current record or it might mean reattempt the failed
command until it starts working.


As COR indicated, the finally block should be used to close resources
and do other necessary cleanup to get your program back to a valid
state. You would want to make sure to clean the resources regardless of
whether a exception is thrown. Consider the following pseudocode:

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
end try

cn.dispose
cn.close

In this case, the connection (an expensive resource) is left open if the
exception is thrown. As an alternative, you can do the following

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
finally
cn.close
cn.dispose
end try

In this case, we are assured that the connection will be closed.
Starting with VB2005, we can change this as follows:

Using cn as new Connection
try
cn.open
catch
messagebox.show("Problem with connection")
end try
end using

Now we are assured that the connection is properly handled as the Using
block handles the dispose for us and closes the connection. Now, if we
want to simply let the exception bubble up to a calling method, we can
trim this down to:

Using cn as new Connection
cn.open
end using

An exception will still be thrown, but the resource will be released
correctly.

Jim Wooley
http://devauthority.com/blogs/jwooley

Mar 17 '06 #26
> Give me an example of an exception that could be thrown that still
allowed the db connection to open. Honestly, I'd like to know. I'm
sure there are some but it seems to me the most likely reason that
line would throw and exception is it couldn't open the db.

second, assume it didn't open the db and then you fall to the finally
section and you try to close a db that isn't open. wouldn't this also
throw and exception?


Ok, I was afraid someone would catch that one. I was trying to be terse while
illustrating the finally portion. Is the following better:
dim cn as new Connection
try
cn.open Throw New ApplicationException catch
messagebox.show("Problem after opening connection")
finally
cn.close
cn.dispose
end try Jim Wooley
http://devauthority.com/blogs/jwooley

Mar 17 '06 #27
cj
At least it must not have been a dumb question. These possible errors
are turning into a vicious loop in my head.

Unfortunately I don't get how your line addition helps things.

I'll have to add this to the many areas to research when I get time.
Jim Wooley wrote:
Give me an example of an exception that could be thrown that still
allowed the db connection to open. Honestly, I'd like to know. I'm
sure there are some but it seems to me the most likely reason that
line would throw and exception is it couldn't open the db.

second, assume it didn't open the db and then you fall to the finally
section and you try to close a db that isn't open. wouldn't this also
throw and exception?


Ok, I was afraid someone would catch that one. I was trying to be terse
while illustrating the finally portion. Is the following better:
dim cn as new Connection
try
cn.open Throw New ApplicationException catch
messagebox.show("Problem after opening connection")
finally
cn.close
cn.dispose
end try Jim Wooley
http://devauthority.com/blogs/jwooley


Mar 17 '06 #28
CJ,

So my code
after the try catch always executes--how is that different from being in
finally?

Put as first statement in your try catch finallly a return (direct after the
try), and debug it, than you see it.

Cor

Mar 17 '06 #29
I was speaking about using the StackTrace and getting line numbers, not ERL.
I never mentioned it, and I've never heard of it. And sort of glad I
hadn't - seems like a horrible way to let people check which line number
caused an error, and hard coding line numbers in their error handling code.

"Jim Wooley" <ji*************@hotmail.com> wrote in message
news:24*************************@msnews.microsoft. com...
You can get line numbers, but that is only good for showing error
messages. It's not like you can in code figure out which function call
caused the error - unless you start hard coding if statements to look
for specific line numbers - but that isn't something you would ever
want to do.

cj wanted to figure out which line of code was causing the problem, to
presumably either have different error handling code, or ignore the
error, etc. That isn't something the stack trace information can
realistically help with.


I think we can agree that using the old On Error GOTO...Resume Next method
is far from ideal. Structured exception handling is a better, more robust
mechanism and would be the prefered method. I am not advocating using the
line numbers and ERL(), more-so mentioning that it is possible.
Not to mention, line numbers come up only when compiled in debug mode.


ERR. Sorry. Thanks for playing. I just tested it in VS2005 and the line
number is retained in a release mode when hard coded as in my sample. You
do not get the line numbers in the stack trace, but ERL() will still
report the line number if it is included in the source code. Hence the
additional overhead. I just checked the sample code with Reflector and the
VB compiler is adding a variable to track the line numbers and
incrementing it interspersed in the code, similar to inserting a
trace.write method in the body of the code. Here's the dis-assembled
version of the previous sample:

Public Shared Sub Main()
Dim num1 As Integer = 10
num1 = 20
Try num1 = 30
num1 = 40
Throw New DivideByZeroException
Catch exception2 As DivideByZeroException
ProjectData.SetProjectError(exception2, num1)
Dim exception1 As DivideByZeroException = exception2
num1 = 60
Console.WriteLine(("Error occured in line: " &
Conversions.ToString(Information.Erl)))
num1 = 70
ProjectData.ClearProjectError
End Try
num1 = 80
Console.ReadLine

As you can see, it works but is far from elegant and the performance
implications are not good.

Mar 17 '06 #30
> At least it must not have been a dumb question. These possible errors
are turning into a vicious loop in my head.
Unfortunately I don't get how your line addition helps things.


Ok. In the new addition, there is some other exception that is thrown other
than creating the connection. It could be due to a null in the database that
is not handled by the data reader, a column that is removed from the database,
a database timeout, anything. The key here being, you need to reclaim the
resource and not just leave it hanging. The best ways to do this are in the
Finally block or with the Using statement.

Jim Wooley

dim cn as new Connection
try
cn.open

Throw New ApplicationException
catch
messagebox.show("Problem after opening connection")
finally
cn.close
cn.dispose
end try
Jim Wooley
http://devauthority.com/blogs/jwooley

Mar 17 '06 #31
> dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
end try

cn.dispose
cn.close

In this case, the connection (an expensive resource) is left open if the
exception is thrown.


No it isn't. The code following the End Try will execute. Bad example in
several ways: if an exception is thrown then one presumes that the
connection failed to open, so no resource is used. But, in any case, the
code following the End Try will execute, so if the connection had opened and
then thrown an exception, it would have been disposed and closed.

[Finally, surely the connection should be closed and then disposed]

Charles
"Jim Wooley" <ji*************@hotmail.com> wrote in message
news:24*************************@msnews.microsoft. com...
I guess I'll have to do some reading on finally. I'm still not sure I
see the use. Perhaps it's how I'm using try catch. My purpose in
using try catch is that without it, or some other error handling, if a
command throws an exception the program halts with some garbage on the
screen. I've written my program with try catch around statements like
calls to other servers where something like a cable being cut might
cause the line to throw and exception as it can not execute. In the
catch I want to know what command is giving the problem. That'll help
me know what is wrong. I print a custom message to indicate what code
is being executed and the ex.message info to the screen for diagnosis.
I need to know which stored procedure will not work, or is it the
request to the remote server or did it try to parse the xml file and
find out it wasn't a xml file? The presence of an error like this can
mean skip the current record or it might mean reattempt the failed
command until it starts working.


As COR indicated, the finally block should be used to close resources and
do other necessary cleanup to get your program back to a valid state. You
would want to make sure to clean the resources regardless of whether a
exception is thrown. Consider the following pseudocode:

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
end try

cn.dispose
cn.close

In this case, the connection (an expensive resource) is left open if the
exception is thrown. As an alternative, you can do the following

dim cn as new Connection
try
cn.open
catch
messagebox.show("Problem opening connection")
finally
cn.close
cn.dispose
end try

In this case, we are assured that the connection will be closed. Starting
with VB2005, we can change this as follows:

Using cn as new Connection
try
cn.open
catch
messagebox.show("Problem with connection")
end try
end using

Now we are assured that the connection is properly handled as the Using
block handles the dispose for us and closes the connection. Now, if we
want to simply let the exception bubble up to a calling method, we can
trim this down to:

Using cn as new Connection
cn.open
end using

An exception will still be thrown, but the resource will be released
correctly.

Jim Wooley
http://devauthority.com/blogs/jwooley

Mar 18 '06 #32
> >
If so, the next question is how do I know it was line 2 that threw the
exception and not line 1 or 4?

try
1
2
3
4
5
catch
a
end try

Marina Levit [MVP] wrote:
That's what the Try is for. To do stuff with the assumption that there
are no errors. The catch is to deal with any errors. And the finally is
to run regardless of whether or not there were errors.


you could have several catch statements - If each line could throw a
different type of exception, then the appropriate catch statement would be
used.
following is cut-n-paste from msdn
Try
NextCentury = DateAdd("yyyy", 100, GivenDate)
Catch ThisExcep As System.ArgumentException
' At least one argument has an invalid value.
Catch ThisExcep As ArgumentOutOfRangeException
' The result is later than December 31, 9999.
Catch ThisExcep As InvalidCastException
' GivenDate cannot be interpreted As a date/time.
Catch
' An unforeseen exception has occurred.
Finally
' This block is always executed before leaving.
End Try
Mar 18 '06 #33

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

Similar topics

3
by: Roger Redford | last post by:
Dear experts, I'm trying to learn java on my own. I picked up a sample online, but it is not compiling right: ------------------------------------------------ import java.io.*;
11
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill...
3
by: Pete Davis | last post by:
I've got the following code: try { reader = new StreamReader(configFile); XmlSerializer serializer = new XmlSerializer(typeof(ServerConfig)); config = (ServerConfig)...
8
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block?...
2
by: Ralph Krausse | last post by:
I created a try/catch/finally but when an expection is thrown, the catch does not handle it... (I know this code is wrong, I want to force the error for this example) try { DataSet ds = new...
2
by: Keith Kowalski | last post by:
I anm opening up a text file reading the lines of the file that refer to a tif image in that file, If the tif image does not exist I need it to send an email stating that the file doesn't exist...
6
by: ECathell | last post by:
I am having a problem with my try..catch blocks... I push a button on my form. using SQLDMO I verify the status of the server. If it is off I turn it on. I then run a query that requires a...
7
by: Sean Kirkpatrick | last post by:
I got caught with my pants down the other day when trying to explain Try...Catch...Finally and things didn't work as I had assumed. Perhaps someone can explain to me the purpose of Finally. I've...
12
by: David Lozzi | last post by:
Howdy, I ran into a very interesting issue and I'm curios as to how this is suppose to work. I am using Try...Catch...Finally statements for all database connectivity in my ASP.NET 2.0 web...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
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,...
0
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...

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.