473,471 Members | 1,684 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Throwing exception in a try block?

is it a bad programming design to throw exception in the try block then
catch it??
Nov 17 '05 #1
40 13459
Compared to an "if" statement, yes, very bad.

Nov 17 '05 #2
Compare to anything it's bad.

hope my collage read this.
Kevin
"Mohammad" <m@abdulfatah.net> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
Compared to an "if" statement, yes, very bad.

Nov 17 '05 #3
Hi Kevin,

Depends. For example, if you have a deeply nested procedure, throwing an
exception to exit might be a viable way.
However, normally throwing an exception is costly plus throwing an exception
should signal an error.

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info

"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??

Nov 17 '05 #4
Kevin Yu wrote:
is it a bad programming design to throw exception in the try block then
catch it??


Here are some guidelines that i have formulated after having tried
different strategies of exceptions:

Don't use exceptions to indicate errors you expect to occur.

Don't throw exceptions to "break" the program flow to a specific
catch-handler (goto):

try {
...
if ( unexpectedSituation )
throw new UnexpectedSituation();
...
} catch ( UnexpectedSituation ) {
// this is a complicated way to do goto
}

But if an unhandled exceptional situation occurs, then do what you would
normally do, for eample:

Stream s = new Stream("x");
try {
byte[] data = new byte[4];
int read = 0;
while ( read < data.Length ) {
int r = s.Read(data, read, data.Length - read);
if ( r == 0 )
throw new ParseError("Stream ended before data could be read");
}
return data;
} catch ( InvalidOperationError ) { // unrelated to ParseError
// Reading failed!
} finally {
s.Close();
}

NOTE: you could use: "using (Stream s = new Stream("x")) { ... }"
instead of try/catch.

It is often good to write the code to have minimal try/catch-blocks, for
example if there is a risk that dict[key] may not be a Foo:

Foo foo = (Foo)dict[key];
try {
foo.f(...);
} catch ( FooProcessingException ) {
... // sensible error handler
}

instead of:

try {
((Foo)dict[key]).f(...);
} catch ( FooProcessingException ) {
... // sensible error handler
}

So that error-handling is narrowly applied to the code that is expected
to expose the error.

In general: only catch if you can actually do anyting to remedy the
error, or is at the top of the call-stack. A possible exception is
catching for logging and retrow:

try {
f(...);
catch ( Exception e ) {
Log(e);
throw;
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #5
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??


It depends on what you're doing and why you're doing it. If you're catching
exceptions so that you can do some sort of rollback or cleanup and then
throw (or rethrow) an exception then it could be a fine design. If you're
throwing and catching as a neat-o way of passing data then, it's a bad
design.

What are you doing?
Nov 17 '05 #6
Helge,

If you don't mind, I would like to add that, from my own experience, I
have yet to come across a case where anything can be done to remedy an
error flagged by an excpetion. The only case that comes to mind where
that is actually doable is in the case of parsing strings to other data
types, in which case the error can be corrected by setting the target
variable to some sensible default.

So, again from my own experience, the best thing to do in the case of
an exception is to simply roll back any changes done within the scope
of the operation and letting the excpetion bubble up to the caller.

This can be accomplished without writing any exception handling code by
borrowing the Resource Initlializing is Acquisition (RIIA) idiom from
C++, which is somewhat easy to implement in C# 2.0, as can be seen from
this article: http://www.codeproject.com/csharp/ex...s_generics.asp

I would also like to add that I don't believe that catching exceptions
just to wrap them in custom exceptions and them rethrow them is a good
idea. Same for logging excpetions, which should be done in one place
and one place only for the whole program.

Nov 17 '05 #7
I have posted another thead earlier on the code I am reading, I can see it's
clearly the guy is from a C++ backgroup, he basically try and catching
everything including the integer assignment, so I think he's abusing the try
catch statement, but I can't report to the police. so I asked the question
on the newsgroup, I got different opinions of the try catch block, I mean if
there is an exception, yea, for sure I want to catch it, but if wrapping
everything in the try catch block is the way to go?

I mean how much confidence you need for .NET?

any inside??
Kevin

"Miha Markic [MVP C#]" <miha at rthand com> wrote in message
news:uy**************@TK2MSFTNGP15.phx.gbl...
Hi Kevin,

Depends. For example, if you have a deeply nested procedure, throwing an
exception to exit might be a viable way.
However, normally throwing an exception is costly plus throwing an exception should signal an error.

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info

"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??


Nov 17 '05 #8
Helge
he did the exactly same thing on all the code, I guess that's his fabulous
design.
try {
...
if ( unexpectedSituation )
throw new UnexpectedSituation();
...
} catch ( UnexpectedSituation ) {
// this is a complicated way to do goto
}

"Helge Jensen" <he**********@slog.dk> wrote in message
news:42**************@slog.dk...
Kevin Yu wrote:
is it a bad programming design to throw exception in the try block then
catch it??


Here are some guidelines that i have formulated after having tried
different strategies of exceptions:

Don't use exceptions to indicate errors you expect to occur.

Don't throw exceptions to "break" the program flow to a specific
catch-handler (goto):

try {
...
if ( unexpectedSituation )
throw new UnexpectedSituation();
...
} catch ( UnexpectedSituation ) {
// this is a complicated way to do goto
}

But if an unhandled exceptional situation occurs, then do what you would
normally do, for eample:

Stream s = new Stream("x");
try {
byte[] data = new byte[4];
int read = 0;
while ( read < data.Length ) {
int r = s.Read(data, read, data.Length - read);
if ( r == 0 )
throw new ParseError("Stream ended before data could be read");
}
return data;
} catch ( InvalidOperationError ) { // unrelated to ParseError
// Reading failed!
} finally {
s.Close();
}

NOTE: you could use: "using (Stream s = new Stream("x")) { ... }"
instead of try/catch.

It is often good to write the code to have minimal try/catch-blocks, for
example if there is a risk that dict[key] may not be a Foo:

Foo foo = (Foo)dict[key];
try {
foo.f(...);
} catch ( FooProcessingException ) {
... // sensible error handler
}

instead of:

try {
((Foo)dict[key]).f(...);
} catch ( FooProcessingException ) {
... // sensible error handler
}

So that error-handling is narrowly applied to the code that is expected
to expose the error.

In general: only catch if you can actually do anyting to remedy the
error, or is at the top of the call-stack. A possible exception is
catching for logging and retrow:

try {
f(...);
catch ( Exception e ) {
Log(e);
throw;
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #9
John

don't get me wrong, I just want some justice on someone else's code that I
need to follow and support.

basically he wrap everything in try catch block even when instantiating a
new object, he will check for if the newly created object is null, then
throw and exception, I mean if the new operate fail to instantiate an
instance aka it's out of memory, the runtime will throw and
OutofMemoryException, the guys is clearly came from a C++ background.
anyway, is it a good idea to wrap everything inside a try catch block, I
read somewhere that try block doesn't cost anything, only when exception
occur, it will cost u, so does that mean it's a good idea to wrap everything
in try catch, I mean hack, this will make the system *Robus*.

enlighten me.

Kevin

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Of**************@TK2MSFTNGP09.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??

It depends on what you're doing and why you're doing it. If you're

catching exceptions so that you can do some sort of rollback or cleanup and then
throw (or rethrow) an exception then it could be a fine design. If you're
throwing and catching as a neat-o way of passing data then, it's a bad
design.

What are you doing?

Nov 17 '05 #10
My opinion is that this can be used sparingly when it makes the code
flow
easier to read. So if I have a catch that basically returns false on an
error, sets
an error message etc. and I have a invariant error that should also
return
false, then it is very simple to throw an exception on an invariant
error and
just reuse the code block in the catch. In other words, I think
throwing an
exception in the try block is acceptable when it makes the code easier
to read
and follow and understand what is going on. Else I don't throw
exceptions in
try.

Regards,
Jeff
is it a bad programming design to throw exception in the try block then
catch it??
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 17 '05 #11
Miha,

good to hear from you again, I think you help me out couple of years ago on
the dataset stuff, nice to see you are active in this newsgroup.
Kevin

"Miha Markic [MVP C#]" <miha at rthand com> wrote in message
news:uy**************@TK2MSFTNGP15.phx.gbl...
Hi Kevin,

Depends. For example, if you have a deeply nested procedure, throwing an
exception to exit might be a viable way.
However, normally throwing an exception is costly plus throwing an
exception should signal an error.

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info

"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??


Nov 17 '05 #12

"Jeff Louie" <je********@yahoo.com> wrote in message
news:e1**************@TK2MSFTNGP12.phx.gbl...
My opinion is that this can be used sparingly when it makes the code
flow
easier to read. So if I have a catch that basically returns false on an
error, sets
an error message etc. and I have a invariant error that should also
return
false, then it is very simple to throw an exception on an invariant
error and
just reuse the code block in the catch. In other words, I think
throwing an
exception in the try block is acceptable when it makes the code easier
to read
and follow and understand what is going on. Else I don't throw
exceptions in
try.

throwing an exception in the try block is costly, it slows down the prog,
yea, it make the code easier to read,
I think with a better refactory technique such design can be avoided. in my
case ( the code I am reading) it's messy
because even in the catch block, and try catch block is also there in case
of the exception occur in the catch block from
writing the error to eh event log. I mean how many level of exception
handling u need.

making the program easier to read doesn't mean you can throw exceptions
freely, for example, in the main function, there is a
try can catch block, then in the try catch, there are bunch of high level
function calls, within those functions, a try catch block
is used to handle any exception that might occur, but then after handling
the exception, e.g write error event log or email people
the function will throw the exception/bubble it up to the main function, in
stead of doing that, why doesn't it just return a bool
then base on the boolean an if statement can direct the program flow instead
of getting to the exception handler that way, sometimes
there is a finally block to clean up stuff, if and object didn't even get
instantiated or started because of the proceeding exception, then no need to
do the
clean up for those object, I mean sure you can use if statement to check if
not null or something before cleaning up or aborting a thread, then
where is the efficiency?



Regards,
Jeff
is it a bad programming design to throw exception in the try block then
catch it??
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 17 '05 #13
Kevin Yu <ko**@hotmail.com> wrote:
throwing an exception in the try block is costly, it slows down the
prog, yea, it make the code easier to read, I think with a better
refactory technique such design can be avoided. in my case ( the code
I am reading) it's messy because even in the catch block, and try
catch block is also there in case of the exception occur in the catch
block from writing the error to eh event log. I mean how many level
of exception handling u need.


Throwing an exception is *slightly* costly - but not very expensive
really. You don't want to start doing it in a short loop, for instance,
but exceptions aren't nearly as expensive as a lot of people seem to
think. In the very rare cases where it makes the code significantly
more readable, I'd hold that as more important than performance until
it was proven that that bit of code was an application bottleneck and
that the exceptions were the problem.

As an example of how overblown the issue of the performance penalty for
exceptions is, on another group a while ago someone was asking whether
or not his application was suffering because it was throwing a couple
of hundred exceptions per *hour*. Many people said that yes, this was
probably slowing his application down significantly. My laptop can
throw a hundred thousand exceptions per *second* - in other words, his
200 exceptions would take less than a millionth of the hour in which
they were thrown.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14
Mohammad wrote:
Helge,

If you don't mind, I would like to add that, from my own experience, I
have yet to come across a case where anything can be done to remedy an
error flagged by an excpetion.
Retrying an operation, for example:

- When a protocol over an unreliable media comes out of sync.
- When a modem dial-up fails
- When a user can be asked to enter another possibility
that is actually doable is in the case of parsing strings to other data
types, in which case the error can be corrected by setting the target
variable to some sensible default.
Which is a kind of "else-if-by-error".

This kind of "recovery-by-default" is usually not a good idea (atleast
in the long run) since it removes the possibility of the caller noticing
that the default was chosen instead of the selected value (which was
misspelled and thus gave a parse-error).
So, again from my own experience, the best thing to do in the case of
an exception is to simply roll back any changes done within the scope
of the operation and letting the excpetion bubble up to the caller.
I couldn't agree more :)

If you are at the top of the callstack you *do* get a special
obligation, to log or whatnot, since the exception would otherwise pass
out of history.
This can be accomplished without writing any exception handling code by
borrowing the Resource Initlializing is Acquisition (RIIA) idiom from
C++, which is somewhat easy to implement in C# 2.0, as can be seen from
this article: http://www.codeproject.com/csharp/ex...s_generics.asp
"finally" is also nice, when the cleanup code isn't reusable.

RIIA is a great idiom, and fits *so* nicely into the C# using-syntax.
You can (relatively) easily move repeated cleanup from "finally"-clauses
to RIAA/using:

class SuspendUpdate: IDisposable {
readonly Control control;
public SuspendUpdate(Control control) {
this.control = control;
control.SuspendLayout();
}
public void Dispose() { control.ResumeLayOut(); }
public ~SuspendUpdate() {
throw new InvalidProgram(
string.Format("Forgot to Dispose {0}", this.GetType().FullName));
}
}
I would also like to add that I don't believe that catching exceptions
just to wrap them in custom exceptions and them rethrow them is a good
My opinion exactly. wrapping is evil, for one thing it destroys the
possibility to "catch-by-type".

The only catch/rethrow I do is when (usually due to rather poor design)
a subcomponent has to iterate through several operations:

IDictionary exceptions = new Hashtable();
foreach ( Foo foo in container )
try {
foo.f();
} catch ( Exception e) {
exceptions.Add(foo, e);
}
}
if ( exceptions.GetEnumerator().MoveNext() )
throw new SomeOperationsFailed(exceptions);

I prefer doing a callback in this situation, but somethimes the
interface is locked down due to years of use by customers.
idea. Same for logging excpetions, which should be done in one place
and one place only for the whole program.


Well,... yes -- but sometimes components wish to keep separate logs of
unexpected errors, for example to prove that it's the caller that's
doing things wrong. That's when:

try {
f();
} catch ( Exception e ) {
Log(e);
throw; // notice: rethrow!
}

comes in handy.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #15
Kevin Yu wrote:
basically he wrap everything in try catch block even when instantiating a
new object, he will check for if the newly created object is null, then
throw and exception, I mean if the new operate fail to instantiate an
instance aka it's out of memory, the runtime will throw and
OutofMemoryException, the guys is clearly came from a C++ background.
None of these things are good behaviour in C++ either :)

BTW: The default operator new should throw on out-of-memory errors, you
need to use "new(nothrow) Foo(...)" to get a null-pointer.
anyway, is it a good idea to wrap everything inside a try catch block, I
read somewhere that try block doesn't cost anything, only when exception
occur, it will cost u, so does that mean it's a good idea to wrap everything
in try catch, I mean hack, this will make the system *Robus*.
Getting a bit on the sarcastic side, aren't you :)
enlighten me.


C++ doesn't have finally, so unless you RIAA you get:

Transaction t = Transaction(...);
try {
t.foo();
} catch ( ... ) {
t.Rollback();
throw;
}
t.Commit();

Which is ok in my book. (I would prefer RIAA on Transaction, but if it's
only in a few places...)

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #16
As an example of how overblown the issue of the performance penalty for
exceptions is, on another group a while ago someone was asking whether
or not his application was suffering because it was throwing a couple
of hundred exceptions per *hour*. Many people said that yes, this was
probably slowing his application down significantly.


Hehe :-)

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
www.rthand.com
SLODUG - Slovene Developer Users Group www.codezone-si.info
Nov 17 '05 #17
hi All

After all these discussions, I only have couple of questions here.

1. is it a good idea to wrap everything in try catch block? explain in
evidence/examples please.

2. is throwing exception in a try catch block a good idea? can Goto be an
alternative??

3. is rethrowing an exception a good design pattern or necessary? I mean
instead of returning a boolean

Kevin
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??

Nov 17 '05 #18
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:e9****************@tk2msftngp13.phx.gbl...
John

don't get me wrong, I just want some justice on someone else's code that I
need to follow and support.

basically he wrap everything in try catch block even when instantiating a
new object, he will check for if the newly created object is null, then
throw and exception, I mean if the new operate fail to instantiate an
instance aka it's out of memory, the runtime will throw and
OutofMemoryException, the guys is clearly came from a C++ background.
anyway, is it a good idea to wrap everything inside a try catch block, I
No, it is not a good idea to wrap everything in a try/catch block. Don't
use try/catch unless you have a real reason to catch an exception or cleanup
(finally). What does the catch do? If it just rethrows the exception, then
you're wasting your effort, making your code hard to read and not adding any
value.

You might remind this guy that he can still check things and throw
exceptions without wrapping the code in a try/catch.
read somewhere that try block doesn't cost anything, only when exception
occur, it will cost u, so does that mean it's a good idea to wrap
everything
That is true, try/catch is almost free until an exception is thrown.
in try catch, I mean hack, this will make the system *Robus*.

enlighten me.

Kevin

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Of**************@TK2MSFTNGP09.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
> is it a bad programming design to throw exception in the try block then
> catch it??
>


It depends on what you're doing and why you're doing it. If you're

catching
exceptions so that you can do some sort of rollback or cleanup and then
throw (or rethrow) an exception then it could be a fine design. If
you're
throwing and catching as a neat-o way of passing data then, it's a bad
design.

What are you doing?


Nov 17 '05 #19
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:On**************@TK2MSFTNGP09.phx.gbl...
hi All

After all these discussions, I only have couple of questions here.

1. is it a good idea to wrap everything in try catch block? explain in
evidence/examples please.
Yes and no. It's a very good idea to have a try/catch at the very top of
your program so that you can properly record exceptions. You actually get
this without writing any code, if an exception bubbles all they way up the
last chance exception handler shows you the call stack and exception and the
program exits. If that's acceptable, you don't have to do anything. If you
want to do something else, like write the exception to a log, use a single
try/catch at the top of your program.

After that, don't add a try/catch/finally unless you have a reason to.

2. is throwing exception in a try catch block a good idea? can Goto be an
alternative??
Yes, if you have an exception the best way to report it is to throw an
exception. I don't see how goto would be useful for reporting an
exceptional condition.

3. is rethrowing an exception a good design pattern or necessary? I mean
instead of returning a boolean
There's no one right answer. First, don't catch the exception unless you
have a reason. If you're just rethrowing it, then it's a waste. There are
plenty of cases where you can catch an exception and return true or false
but those would be expected exceptions (FormatExceptions etc). In general,
you want to rethrow the exception because it contains a lot of information
that will help you solve the problem. You don't want to get into a
situation where all of your methods return true or false to indicate an
error and you call GetLastException to find out what the error was.


Kevin
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??


Nov 17 '05 #20
John

"No, it is not a good idea to wrap everything in a try/catch block. Don't
use try/catch unless you have a real reason to catch an exception or
cleanup
(finally). What does the catch do? If it just rethrows the exception,
then
you're wasting your effort, making your code hard to read and not adding
any
value."

In the catch block, the error will be log to the windows event log, then the
exception
is wrapped into a custom exception and rethrown. not sure if this is a good
idea.

There are different type of exception, if it's application critical input
parameters such
as those read from the application config file/console input (console app
called by
windows service by spawning a process and pass parameters), if those values
are incorrect or corrupted which
are unlikely, then an exception should be thrown to stop the execution. with
the throwing
exception in the try catch block, it will easy stop the application whenever
a parameter
is incorrect. I mean using goto or continue statement will do but in terms
of handling the situation,
I think throwing exception will make more sense.

so in this case, do this:

try
{
if (error)
throw new exception("Error");
}
catch (Exception ex)
{
Logerror();
}
won't be so bad.

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:eu**************@TK2MSFTNGP10.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:e9****************@tk2msftngp13.phx.gbl...
John

don't get me wrong, I just want some justice on someone else's code that I need to follow and support.

basically he wrap everything in try catch block even when instantiating a new object, he will check for if the newly created object is null, then
throw and exception, I mean if the new operate fail to instantiate an
instance aka it's out of memory, the runtime will throw and
OutofMemoryException, the guys is clearly came from a C++ background.
anyway, is it a good idea to wrap everything inside a try catch block, I
No, it is not a good idea to wrap everything in a try/catch block. Don't
use try/catch unless you have a real reason to catch an exception or

cleanup (finally). What does the catch do? If it just rethrows the exception, then you're wasting your effort, making your code hard to read and not adding any value.

You might remind this guy that he can still check things and throw
exceptions without wrapping the code in a try/catch.
read somewhere that try block doesn't cost anything, only when exception
occur, it will cost u, so does that mean it's a good idea to wrap
everything


That is true, try/catch is almost free until an exception is thrown.
in try catch, I mean hack, this will make the system *Robus*.

enlighten me.

Kevin

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Of**************@TK2MSFTNGP09.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
> is it a bad programming design to throw exception in the try block then > catch it??
>

It depends on what you're doing and why you're doing it. If you're

catching
exceptions so that you can do some sort of rollback or cleanup and then
throw (or rethrow) an exception then it could be a fine design. If
you're
throwing and catching as a neat-o way of passing data then, it's a bad
design.

What are you doing?



Nov 17 '05 #21
Kevin Yu wrote:
In the catch block, the error will be log to the windows event log, then the
exception
Okay, that's reasonable... if you expect the caller to just die or
mishandle the exception.
is wrapped into a custom exception and rethrown. not sure if this is a good
idea.
Now *that*'s my favorite hate-thing on exceptions!

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

(As you may be able to tell, this is not my first discussion on the
subject :)
try
{
if (error)
throw new exception("Error");
}
catch (Exception ex)
{
Logerror();
}


I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingException(
string.Format("Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_Main(valid_args), 0);

ParseException threw = null;
try {
_Main(invalid_args);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(ParseException);
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #22

Helge Jensen wrote:
Retrying an operation, for example:

- When a protocol over an unreliable media comes out of sync.
- When a modem dial-up fails
- When a user can be asked to enter another possibility
Touché :)
Which is a kind of "else-if-by-error".

This kind of "recovery-by-default" is usually not a good idea (atleast in the long run) since it removes the possibility of the caller noticing that the default was chosen instead of the selected value (which was
misspelled and thus gave a parse-error).
Well, in this particular case, it would have been great if the
framework contained a sort of "CanParse" function. So instead of
calling Int32.Parse and bracing for the exception to hit, I would have
preferred to call Int32.CanParse and THEN do some action.
Well,... yes -- but sometimes components wish to keep separate logs of unexpected errors

Touché again.

Nov 17 '05 #23
Well, in this particular case, it would have been great if the
framework contained a sort of "CanParse" function. So instead of
calling Int32.Parse and bracing for the exception to hit, I would have
preferred to call Int32.CanParse and THEN do some action.


There is ...

double.TryParse() and there are arguments that let you specify the data
type.

Whidbey has more methods besides that one.

Nov 17 '05 #24

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

Except that in v1.1 using a naked throw causes the stack trace to get reset,
so you lose that information.

I prefer to catch-wrap-throw, as nothing is lost and you can add context
information. I use a helper method to
rethrow the original exception type, as in...

catch(Exception ex)
{
throw CloneException("Context info.",ex);
}

This preserves the original exception type, the stack trace info, and adds
additional meaning.

I really don't like that, it's just a very complicated way of doing goto,
and there are better options: write one logging handler at the call-stack
top, and then use exceptions to signal errors, knowing that someone will
catch, log, and whatever they feel is approrpriate.


I prefer a log twice option, the first time at the original site where the
exception was caught, and once again at the top. The reason is to catch code
paths where an exception is inadvertently swallowed on its way up the call
stack. This can be a problem in a large project with many different
components written by different developers - no one person has personal
knowledge of every piece of code in the system.

Nov 17 '05 #25
David Levine wrote:
Except that in v1.1 using a naked throw causes the stack trace to get reset,
so you lose that information.
Yes, that's a bug. But the original trace is in the log, that's why you
did the catch, so it's not that bad.
I prefer to catch-wrap-throw, as nothing is lost and you can add context
information. I use a helper method to
rethrow the original exception type, as in...

catch(Exception ex)
{
throw CloneException("Context info.",ex);
}
That's not really wrapping, is it? That's working around the
"throw;"-bug. At least if you really are "cloning" ex.

A nice workaround :)
This preserves the original exception type, the stack trace info,
yes.
and adds
additional meaning.


Only if the "Context info" doesn't shadow the information in ex, but is
made available on enquery.

It's a nice trick though, It (in effect) allows adding notes to an
exception in the form of objects not available at the error-site, but
non-theless important to understanding the error as the exception
bubbles the call-stack.
I really don't like that, it's just a very complicated way of doing goto,
and there are better options: write one logging handler at the call-stack
top, and then use exceptions to signal errors, knowing that someone will
catch, log, and whatever they feel is approrpriate.


I prefer a log twice option, the first time at the original site where the
exception was caught, and once again at the top. The reason is to catch code
paths where an exception is inadvertently swallowed on its way up the call
stack. This can be a problem in a large project with many different
components written by different developers - no one person has personal
knowledge of every piece of code in the system.


I recognize this problem, people writing:

try {
f();
} catch {};

should get a *very* serious talking-to.

But how does the above help you with that?

It must be a very involved logfile-analysis to extract the relevant
information, especially since there is nothing that warns you this may
be the problem. The program explicitly *doesn't* terminate.

How do you skip all the places where actual error-handling is done?

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #26
David,
| I prefer a log twice option, the first time at the original site where the
| exception was caught, and once again at the top. The reason is to catch
code
Have you looked at the new .NET 2.0 AppDomain events pertaining to
Exceptions?

http://msdn2.microsoft.com/library/1dw188c1.aspx

Such as CatchingException & ExceptionThrown. I have not tried it, reading
about ExceptionThrown, it sounds like it may allow one to log the exception
at the original site, instead of splattering your code with a lot of Catch
blocks...

I would be curious on your take on the exceptions after you have had a
chance to use them.

Just a thought
Jay
"David Levine" <no******************@wi.rr.com> wrote in message
news:uT**************@TK2MSFTNGP10.phx.gbl...
|
| >
| > What does wrapping it help the caller? Logging certainly didn't produce
| > any additional information the caller would like to have.
| >
| > More importantly, you have robbed the caller of the possibility to catch
| > the exception by type, just use:
| >
| > catch ( Exception e ) {
| > Log(e);
| > throw;
| > }
| >
|
| Except that in v1.1 using a naked throw causes the stack trace to get
reset,
| so you lose that information.
|
| I prefer to catch-wrap-throw, as nothing is lost and you can add context
| information. I use a helper method to
| rethrow the original exception type, as in...
|
| catch(Exception ex)
| {
| throw CloneException("Context info.",ex);
| }
|
| This preserves the original exception type, the stack trace info, and adds
| additional meaning.
|
| >
| > I really don't like that, it's just a very complicated way of doing
goto,
| > and there are better options: write one logging handler at the
call-stack
| > top, and then use exceptions to signal errors, knowing that someone will
| > catch, log, and whatever they feel is approrpriate.
|
| I prefer a log twice option, the first time at the original site where the
| exception was caught, and once again at the top. The reason is to catch
code
| paths where an exception is inadvertently swallowed on its way up the call
| stack. This can be a problem in a large project with many different
| components written by different developers - no one person has personal
| knowledge of every piece of code in the system.
|
|
|
|
|
Nov 17 '05 #27

"Helge Jensen" <he**********@slog.dk> wrote in message
news:42**************@slog.dk...
Kevin Yu wrote:
In the catch block, the error will be log to the windows event log, then the exception
Okay, that's reasonable... if you expect the caller to just die or
mishandle the exception.
is wrapped into a custom exception and rethrown. not sure if this is a good idea.


Now *that*'s my favorite hate-thing on exceptions!

What does wrapping it help the caller? Logging certainly didn't produce
any additional information the caller would like to have.

well, I think the purpose of making a custom exception is to include more
information for the exception,
sometimes, people want to log and error source such as the machine name or
IP, information like that.
and use the original exception as inner exception.


More importantly, you have robbed the caller of the possibility to catch
the exception by type, just use:

catch ( Exception e ) {
Log(e);
throw;
}

(As you may be able to tell, this is not my first discussion on the
subject :)
try
{
if (error)
throw new exception("Error");
}
catch (Exception ex)
{
Logerror();
}


I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingException(
string.Format("Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_Main(valid_args), 0);

ParseException threw = null;
try {
_Main(invalid_args);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(ParseException);
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #28
try
{
if (error)
throw new exception("Error");
}
catch (Exception ex)
{
Logerror();
}
I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

I don't know if it's a bug or not, in a timer_elapsed event handler, if an
exception occur,
it won't bubble back to the caller, since it's running in another thread, so
if there is
no try catch block to handle the exception in the elapsed event handler and
returning a value,
then the user won't event know exception occur in the handler.

[STAThread]

static void Main(string[] args)

{
System.Timers.Timer myTimer = new System.Timers.Timer(5000);
myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed) ;

myTimer.Start();

Console.ReadLine();

}

private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)

{

Console.WriteLine("Time elapsed");

throw new Exception("Exception from elapsed event handler");

}

static int _Main(string args[]) {
// just code along, and throw INFORMATIONAL errors
// if anything goes wrong.
if ( error )
throw new ParsingException(
string.Format("Invalid argument {0}", arg))
// ...
return 0;
}

static int Main(string args[]) {
#if !DEBUG
try {
#endif
return _Main(args);
#if !DEBUG
} catch ( Exception e ) {
Log(e);
throw;
#endif
}

The (#if !DEBUG) allows you to use the "break if not catched" setting in
the IDE usefully. You could use another symbol, DEBUG is just *so* handy
for me :)

This pattern is also pretty usefull when testing:

void Test() {
string[] valid_args = { "x" };
string[] invalid_args = { "y" };

AssertEquals(_Main(valid_args), 0);

ParseException threw = null;
try {
_Main(invalid_args);
} catch ( ParseException e ) {
threw = e;
}
AssertNull(ParseException);
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 17 '05 #29
Doh!
| I would be curious on your take on the exceptions after you have had a
| chance to use them.
I would be curious on your take on the new exception events after you have
had a chance to use them.

Jay

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:Og****************@TK2MSFTNGP10.phx.gbl...
| David,
|| I prefer a log twice option, the first time at the original site where
the
|| exception was caught, and once again at the top. The reason is to catch
| code
| Have you looked at the new .NET 2.0 AppDomain events pertaining to
| Exceptions?
|
| http://msdn2.microsoft.com/library/1dw188c1.aspx
|
| Such as CatchingException & ExceptionThrown. I have not tried it, reading
| about ExceptionThrown, it sounds like it may allow one to log the
exception
| at the original site, instead of splattering your code with a lot of Catch
| blocks...
|
| I would be curious on your take on the exceptions after you have had a
| chance to use them.
|
| Just a thought
| Jay
|
|
| "David Levine" <no******************@wi.rr.com> wrote in message
| news:uT**************@TK2MSFTNGP10.phx.gbl...
||
|| >
|| > What does wrapping it help the caller? Logging certainly didn't produce
|| > any additional information the caller would like to have.
|| >
|| > More importantly, you have robbed the caller of the possibility to
catch
|| > the exception by type, just use:
|| >
|| > catch ( Exception e ) {
|| > Log(e);
|| > throw;
|| > }
|| >
||
|| Except that in v1.1 using a naked throw causes the stack trace to get
| reset,
|| so you lose that information.
||
|| I prefer to catch-wrap-throw, as nothing is lost and you can add context
|| information. I use a helper method to
|| rethrow the original exception type, as in...
||
|| catch(Exception ex)
|| {
|| throw CloneException("Context info.",ex);
|| }
||
|| This preserves the original exception type, the stack trace info, and
adds
|| additional meaning.
||
|| >
|| > I really don't like that, it's just a very complicated way of doing
| goto,
|| > and there are better options: write one logging handler at the
| call-stack
|| > top, and then use exceptions to signal errors, knowing that someone
will
|| > catch, log, and whatever they feel is approrpriate.
||
|| I prefer a log twice option, the first time at the original site where
the
|| exception was caught, and once again at the top. The reason is to catch
| code
|| paths where an exception is inadvertently swallowed on its way up the
call
|| stack. This can be a problem in a large project with many different
|| components written by different developers - no one person has personal
|| knowledge of every piece of code in the system.
||
||
||
||
||
|
|
Nov 17 '05 #30
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:u%****************@TK2MSFTNGP14.phx.gbl...
> try
> {
> if (error)
> throw new exception("Error");
> }
> catch (Exception ex)
> {
> Logerror();
> }


I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

I don't know if it's a bug or not, in a timer_elapsed event handler, if an
exception occur,
it won't bubble back to the caller, since it's running in another thread,
so
if there is
no try catch block to handle the exception in the elapsed event handler
and
returning a value,
then the user won't event know exception occur in the handler.


You can use AppDomain.UnhandledException event to handle events from all
threads.
It's not quite the same as catching them since you can't continue.

Nov 17 '05 #31
Kevin Yu wrote:
I don't know if it's a bug or not, in a timer_elapsed event handler, if an
exception occur,
it won't bubble back to the caller, since it's running in another thread, so
if there is
no try catch block to handle the exception in the elapsed event handler and
returning a value,
then the user won't event know exception occur in the handler.


That's the way (and the only viable) way that uncaught exceptions work.
The solution is that top-of-callstack methods *need* to consider what to
do when exceptions occur. This is equally relevant no matter how you use
exceptions.

Usually you don't write code directly into the thread-startable fuction,
but write it instead so that it can be invoked normally:

private static void f(ArgType1 arg1, ArgType2 arg2) { ... }

private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
try {
f((ArgType1)arg1, new ArgType2(...));
} catch ( Exception e ) {
Global.Log(e);
}
}

Further, you can add to the UnhandledException event in AppDomain to
spot where this rule is broken at runtime. And you can even Log from
there so you have a traceback for finding the culprit.

It would be nice with a thread-local UnhandledException, but it's really
not *that* often it would make sense, and you can implement your own
helper-class for it:

class LocalRun {
public public readonly Delegate F;
public public object[] args;
public event UnhandledExceptionEventHandler UnhandledException;
public LocalRun(Delegate F, object[] args) {
this.F = F;
this.args = args;
}
public void Run() {
try {
F.DynamicInvoke(args);
} catch ( Exception e ) {
try {
UnhandledException(e);
} catch ( Exception e ) {
// special defence against UnhandledException throwing required
// this is basically the only catch { /*ignore */ } that
// makes sense
}
throw;
}
}
}

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #32

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Oi**************@TK2MSFTNGP14.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:u%****************@TK2MSFTNGP14.phx.gbl...

> try
> {
> if (error)
> throw new exception("Error");
> }
> catch (Exception ex)
> {
> Logerror();
> }

I really don't like that, it's just a very complicated way of doing
goto, and there are better options: write one logging handler at the
call-stack top, and then use exceptions to signal errors, knowing that
someone will catch, log, and whatever they feel is approrpriate.

I don't know if it's a bug or not, in a timer_elapsed event handler, if an exception occur,
it won't bubble back to the caller, since it's running in another thread, so
if there is
no try catch block to handle the exception in the elapsed event handler
and
returning a value,
then the user won't event know exception occur in the handler.


You can use AppDomain.UnhandledException event to handle events from all
threads.
It's not quite the same as catching them since you can't continue.

no, looks like the AppDomain.UnhandledException event can't pick up the
exception either.


Nov 17 '05 #33
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:OU**************@tk2msftngp13.phx.gbl...

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Oi**************@TK2MSFTNGP14.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:u%****************@TK2MSFTNGP14.phx.gbl...
>
>>
>> > try
>> > {
>> > if (error)
>> > throw new exception("Error");
>> > }
>> > catch (Exception ex)
>> > {
>> > Logerror();
>> > }
>>
>> I really don't like that, it's just a very complicated way of doing
>> goto, and there are better options: write one logging handler at the
>> call-stack top, and then use exceptions to signal errors, knowing that
>> someone will catch, log, and whatever they feel is approrpriate.
>>
>
>
> I don't know if it's a bug or not, in a timer_elapsed event handler, if an > exception occur,
> it won't bubble back to the caller, since it's running in another thread, > so
> if there is
> no try catch block to handle the exception in the elapsed event handler
> and
> returning a value,
> then the user won't event know exception occur in the handler.
>


You can use AppDomain.UnhandledException event to handle events from all
threads.
It's not quite the same as catching them since you can't continue.

no, looks like the AppDomain.UnhandledException event can't pick up the
exception either.


The exception is passed to the event handler in the ExceptionObject property
of the UnhandledExceptionEventArgs argument.
Nov 17 '05 #34

"Helge Jensen" <he**********@slog.dk> wrote in message
news:O7*************@TK2MSFTNGP12.phx.gbl...
David Levine wrote:
Except that in v1.1 using a naked throw causes the stack trace to get
reset, so you lose that information.
Yes, that's a bug. But the original trace is in the log, that's why you
did the catch, so it's not that bad.


It's only in the log if the catch routine logs it - mine does, but not
everyone does so.
I prefer to catch-wrap-throw, as nothing is lost and you can add context
information. I use a helper method to
rethrow the original exception type, as in...

catch(Exception ex)
{
throw CloneException("Context info.",ex);
}
That's not really wrapping, is it? That's working around the "throw;"-bug.
At least if you really are "cloning" ex.


Actually it really is wrapping. The routine CloneException uses reflection
to create an instance of the exception that was originally caught, passing
the original exception to the constructor as the InnerException. It looks
something like this...

static public System.Exception CloneException(string
message,System.Exception ex)
{
Type t = ex.GetType();
try
{
if ( t.IsSubclassOf(typeof(System.Exception)) )
{
Type[] types = new Type[2] { typeof(string),typeof(System.Exception) };
object[] args = new object[] {message,ex};
ConstructorInfo ci = t.GetConstructor(types);
if ( ci != null )
{
object o;
o = t.Assembly.CreateInstance(
t.FullName,false,BindingFlags.CreateInstance,null, args,null,null );
return (System.Exception)o;
}
}
}
catch(Exception uhOh)
{
SwallowException(uhOh,"Unable to CloneException of type {0}.",t ); //
trace it
}
// if here it was unable to create an instance of the same type. Create a
generic exception
// and return that.
return new System.Exception(message,ex);
} // CloneException

A nice workaround :)
thanks!
This preserves the original exception type, the stack trace info,
yes.
and adds additional meaning.


Only if the "Context info" doesn't shadow the information in ex, but is
made available on enquery.


It should be something meaningful otherwise the exception should not be
caught at all. Personally I find error messages that consist solely of "Null
Reference" to be as useless as the more generic "Something's f*&&kd", and a
lot less catchy. And yes, many years ago I inadvertently left that error
message in a shipping product...along with the product manager's home phone
number instead of support

It's a nice trick though, It (in effect) allows adding notes to an
exception in the form of objects not available at the error-site, but
non-theless important to understanding the error as the exception bubbles
the call-stack.
Exactly. It also avoids the use of custom exception types.

I prefer a log twice option, the first time at the original site where
the exception was caught, and once again at the top. The reason is to
catch code paths where an exception is inadvertently swallowed on its way
up the call stack. This can be a problem in a large project with many
different components written by different developers - no one person has
personal knowledge of every piece of code in the system.


I recognize this problem, people writing:

try {
f();
} catch {};

should get a *very* serious talking-to.


Yes but it does happen, especially on a large team where many members are
experienced C/C++ but novice C# developers.

I also provided a routine called SwallowException that is supposed to put
into all catch handlers that do not otherwise log the exception. This has
allowed us to track down a large number of problems that were masked by evil
catch handlers like the one you showed here.

But how does the above help you with that?

It must be a very involved logfile-analysis to extract the relevant
information, especially since there is nothing that warns you this may be
the problem. The program explicitly *doesn't* terminate.

I usually don't want the program to terminate. In our applications most
exceptions do not signify a fatal condition, just one that the program logic
cannot usually automatically recover from... e.g. a "cable disconnected"
fault may be fatal in terms of the task, but not for the entire application.

I also use a fairly sophisticated diagnostic tracing layer that is much more
expressive then the exception logging mechanism.
How do you skip all the places where actual error-handling is done?


It's actually fairly simple although it does use an assumption which may be
incorrect. I use a routine like this...
static internal void PublishExceptionOnCreate(Exception ex)
{
if ( ex == null )
return; // sanity check failed
if ( !PublishOnCreate ) // global flag to disable this
return;
if ( ex.InnerException != null && ex.InnerException.InnerException !=
null )
return; // not first create call, so don't publish - **this is the
assumtion**
// this is used when an internal error occurs - don't try to publish it on
create
// because it might cause endless recursion.
if ( ex.GetType() == typeof(CustomPublisherException) )
return;
Publish(ex); // if here then publish
}
The key is the assumption that if the InnerException is ever not null then
it has already been published, because this implies that the exception has
already gone through a catch-wrap-throw phase and so has already been
published (the first time it was caught). I know that this will not always
be correct, but in practice it actually works rather well because so long
as all catch handlers use the same exception management layer (mine) it will
always use the same heuristics. And the worst that happens is that it gets
published a few too many times. In a properly designed system you should not
be getting flooded with exceptions, otherwise you've got bigger problems
then a few extra entries in a log file.

Nov 17 '05 #35

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:Og****************@TK2MSFTNGP10.phx.gbl...
David,
| I prefer a log twice option, the first time at the original site where
the
| exception was caught, and once again at the top. The reason is to catch
code
Have you looked at the new .NET 2.0 AppDomain events pertaining to
Exceptions?
I looked at them briefly when I played with Whidbey, but unfortunately the
project I am working on now is using the 1.1 framework so I haven't been
able to spend any time on it in months. However, my brief impression is that
a program that throws too many exceptions can really bog the system down
from the events getting fired. This might be a godsend because it might
force a lot of lazy developers to clean up their code :-)

http://msdn2.microsoft.com/library/1dw188c1.aspx

Such as CatchingException & ExceptionThrown. I have not tried it, reading
about ExceptionThrown, it sounds like it may allow one to log the
exception
at the original site, instead of splattering your code with a lot of Catch
blocks...
I agree, I think it will be a really good thing but will also require a log
of discipline. On the whole I think it will encourage good practices,
because otherwise that event will get fired so much the noise will mask out
the really serious exceptions.

I would be curious on your take on the exceptions after you have had a
chance to use them.

Just a thought
Jay

I like them...I wish I was working on a Whidbey-based project. I also
really like generics, partial classes, the improved IDE, etc. MSFT is doing
a great job.


Nov 17 '05 #36

"Helge Jensen" <he**********@slog.dk> wrote in message
news:42**************@slog.dk...
Kevin Yu wrote:
I don't know if it's a bug or not, in a timer_elapsed event handler, if
an
exception occur,
it won't bubble back to the caller, since it's running in another thread,
so
if there is
no try catch block to handle the exception in the elapsed event handler
and
returning a value,
then the user won't event know exception occur in the handler.


That's the way (and the only viable) way that uncaught exceptions work.
The solution is that top-of-callstack methods *need* to consider what to
do when exceptions occur. This is equally relevant no matter how you use
exceptions.
The main problem I have with the UE handler in the v1.1 framework is that
the event is only delivered to subscribers running in the default appdomain.
If your handler is in another appdomain then it will never receive the
notification unless you write your own plumbing.

Usually you don't write code directly into the thread-startable fuction,
but write it instead so that it can be invoked normally:

private static void f(ArgType1 arg1, ArgType2 arg2) { ... }

private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
try {
f((ArgType1)arg1, new ArgType2(...));
} catch ( Exception e ) {
Global.Log(e);
}
}


I usually use a pattern similar to the async threading, where I catch and
save the exception on the worker thread and then rethrow it on the main
thread when it checks the results. Of course, this may not always be
possible but you can always save the exception object for later processing.

Nov 17 '05 #37

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:OE**************@tk2msftngp13.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:OU**************@tk2msftngp13.phx.gbl...

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Oi**************@TK2MSFTNGP14.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:u%****************@TK2MSFTNGP14.phx.gbl...
>
>>
>> > try
>> > {
>> > if (error)
>> > throw new exception("Error");
>> > }
>> > catch (Exception ex)
>> > {
>> > Logerror();
>> > }
>>
>> I really don't like that, it's just a very complicated way of doing
>> goto, and there are better options: write one logging handler at the
>> call-stack top, and then use exceptions to signal errors, knowing that >> someone will catch, log, and whatever they feel is approrpriate.
>>
>
>
> I don't know if it's a bug or not, in a timer_elapsed event handler, if
an
> exception occur,
> it won't bubble back to the caller, since it's running in another thread,
> so
> if there is
> no try catch block to handle the exception in the elapsed event

handler > and
> returning a value,
> then the user won't event know exception occur in the handler.
>

You can use AppDomain.UnhandledException event to handle events from all threads.
It's not quite the same as catching them since you can't continue.

no, looks like the AppDomain.UnhandledException event can't pick up the
exception either.


The exception is passed to the event handler in the ExceptionObject

property of the UnhandledExceptionEventArgs argument.


run this:

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{
AppDomain.CurrentDomain.UnhandledException +=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
System.Timers.Timer myTimer = new System.Timers.Timer(5000);
myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed) ;

myTimer.Start();

Console.ReadLine();

}

private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)

{
Console.WriteLine("in timere elapsed handler, throwing exception...");

throw new Exception("Exception from elapsed event handler");

}

private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)

{

Console.WriteLine("Unhandled exception occured!");

}

}

CurrentDomain_UnhandledException never get called.


Nov 17 '05 #38
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:OB**************@tk2msftngp13.phx.gbl...

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:OE**************@tk2msftngp13.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:OU**************@tk2msftngp13.phx.gbl...
>
> "John Vottero" <Jo**@mvpsi.com> wrote in message
> news:Oi**************@TK2MSFTNGP14.phx.gbl...
>> "Kevin Yu" <ko**@hotmail.com> wrote in message
>> news:u%****************@TK2MSFTNGP14.phx.gbl...
>> >
>> >>
>> >> > try
>> >> > {
>> >> > if (error)
>> >> > throw new exception("Error");
>> >> > }
>> >> > catch (Exception ex)
>> >> > {
>> >> > Logerror();
>> >> > }
>> >>
>> >> I really don't like that, it's just a very complicated way of doing
>> >> goto, and there are better options: write one logging handler at
>> >> the
>> >> call-stack top, and then use exceptions to signal errors, knowing that >> >> someone will catch, log, and whatever they feel is approrpriate.
>> >>
>> >
>> >
>> > I don't know if it's a bug or not, in a timer_elapsed event handler, if > an
>> > exception occur,
>> > it won't bubble back to the caller, since it's running in another
> thread,
>> > so
>> > if there is
>> > no try catch block to handle the exception in the elapsed event handler >> > and
>> > returning a value,
>> > then the user won't event know exception occur in the handler.
>> >
>>
>> You can use AppDomain.UnhandledException event to handle events from all >> threads.
>> It's not quite the same as catching them since you can't continue.
>
>
> no, looks like the AppDomain.UnhandledException event can't pick up the
> exception either.
The exception is passed to the event handler in the ExceptionObject

property
of the UnhandledExceptionEventArgs argument.


run this:


I can't explain that. It works as expected with a System.Threading.Timer.

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{
AppDomain.CurrentDomain.UnhandledException +=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
System.Timers.Timer myTimer = new System.Timers.Timer(5000);
myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed) ;

myTimer.Start();

Console.ReadLine();

}

private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)

{
Console.WriteLine("in timere elapsed handler, throwing exception...");

throw new Exception("Exception from elapsed event handler");

}

private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)

{

Console.WriteLine("Unhandled exception occured!");

}

}

CurrentDomain_UnhandledException never get called.


Nov 17 '05 #39
Kevin Yu wrote:
no, looks like the AppDomain.UnhandledException event can't pick up the
exception either.

That's because the C# code that runs "event" catches and discards the
exceptions. This bad behaviour is replicated in the threads that runs
events in System.Windows.Forms.

If the event-handler needs to "ignore" exceptions it should at least
notify someone. Best thing would be a place in the resource
(Timer/Control/Thread/...) where you can bind on an UnhandledException,
otherwise AppDomain.UnhandledException.
run this: myTimer.Elapsed +=new System.Timers.ElapsedEventHandler(myTimer_Elapsed) ;
private static void myTimer_Elapsed(object sender,
System.Timers.ElapsedEventArgs e) { throw new Exception("Exception from elapsed event handler"); }
CurrentDomain_UnhandledException never get called.


Because of the try {...} catch { /* ignore */ } policy taken by the code
that executes the ElapsedEvent.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #40
John,
it seems that this programmer is part of you group. Rather than spending
time in here, walk across to her cube and have a polite discussion about the
tenets of good exception practices. I think your approach is not the best
because it doesn't correct the situation.

--
Regards
Alvin Bruney
[Shameless Author Plug]
The Microsoft Office Web Components Black Book with .NET
available at www.lulu.com/owc
--------------------------------------------------
"John Vottero" <Jo**@mvpsi.com> wrote in message
news:Of**************@TK2MSFTNGP09.phx.gbl...
"Kevin Yu" <ko**@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP14.phx.gbl...
is it a bad programming design to throw exception in the try block then
catch it??


It depends on what you're doing and why you're doing it. If you're
catching exceptions so that you can do some sort of rollback or cleanup
and then throw (or rethrow) an exception then it could be a fine design.
If you're throwing and catching as a neat-o way of passing data then, it's
a bad design.

What are you doing?

Nov 17 '05 #41

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

Similar topics

2
by: Hank | last post by:
Please help me diagnose the following problem. I have a Swing program (running under 1.4.2_04) that uses JNI to get some hardware-level information and return that info as a csv String. The...
2
by: SK | last post by:
What is the purpose of throwing exceptions in catch block. Bcos the exception is already thrown only, it is coming to the catch block.What is the purpose of throwing it again then!!!.....Help
21
by: Stephan | last post by:
why does the following code not work???? after compiling and running it will just say killed after all my memory filled up any suggestions? #include <iostream> using namespace std; void...
1
by: Farooq Khan | last post by:
i'm writing a class library having following code snippet. i want this class to report an error (by throwing an Exception) to the application using this class library. the problem is that within...
5
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back...
1
by: paul.hine | last post by:
Hello, I maintain an application that pulls data from a web service and writes it to an Excel sheet. Originally, the app used OleDb to write the Excel. Exports ran fine except that some text...
5
by: Mike | last post by:
Hello All, Please, if anyone can point me to the problem, I'd sure appreciate it! I am very new to VB programming and not a programmer to begin with. This is part of a Visual Basic 2005 Express...
3
by: =?Utf-8?B?SGVtaWw=?= | last post by:
Hi, I have written a web service for accessing data from a database. I have a method in the webservice which returns a dataset. I am trying to implement error handling by using the...
21
by: Chris M. Thomasson | last post by:
Is it every appropriate to throw in a dtor? I am thinking about a simple example of a wrapper around a POSIX file... ________________________________________________________________________ class...
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
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,...
1
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.