By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,386 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,386 IT Pros & Developers. It's quick & easy.

Exception handling suggestions

P: n/a
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException

I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.

What do you suggest?

Zytan

Mar 10 '07 #1
Share this Question
Share on Google+
41 Replies


P: n/a
VJ
main
{
AppDomain.CurrentDomain.UnhandledException+=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
Application.Run(new MyFirstForm());
}

private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exit();

}

That should take care of it..
VJ

"Zytan" <zy**********@yahoo.comwrote in message
news:11**********************@q40g2000cwq.googlegr oups.com...
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException

I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.

What do you suggest?

Zytan

Mar 10 '07 #2

P: n/a
main
{
AppDomain.CurrentDomain.UnhandledException+=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
Application.Run(new MyFirstForm());
}

private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exit();
}
Wow, thanks, VJ. Ok, so what is Application? Is that a name you
made? I am testing this in a console app, and it doesn't exist.

Also, I can't actually test this code, since the debugger always halts
the program on an unhandled exception. How do you test this?

Actually, I was thinking about how do I handle exceptions in which I
don't want the program to quit? For example, for int.Parse(), I just
want to catch everything, and keep the program running, since the data
passed into Parse() could possible be improper, so I want to catch it,
and notify me, but continue running. Is catching Exception really a
good idea?

Zytan

Mar 11 '07 #3

P: n/a
Zytan wrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException

I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.

What do you suggest?

Zytan
If the string really can be null, that is easy to check for. You should
check that before calling the method instead of waiting for the exception.

If you don't really need to determine the exact reason why the string
can't be converted, you can use the int.TryParse method instead. Then
you will not need any exception handling at all.

--
Göran Andersson
_____
http://www.guffa.com
Mar 11 '07 #4

P: n/a
If the string really can be null, that is easy to check for. You should
check that before calling the method instead of waiting for the exception.
Actually, I just do:
int result = int.Parse("0" + s);
so, nulls are handled already.

I'm concerned with s == "ABC". The data that s can be may be warped
sometimes, and this is actually a decent spot to check to ensure it is
not warped.
If you don't really need to determine the exact reason why the string
can't be converted, you can use the int.TryParse method instead. Then
you will not need any exception handling at all.
Ah, ok, thanks, Göran!

Zytan

Mar 11 '07 #5

P: n/a
VJ
yes as Goran says its better to safe, than sorry.. but again what I gave is
unexpected situations at a global level.. That is provided by the .NET
environment, for windows applications. Also as note... each try/catch block
is expensive so try to minimze them, and check your parameters before you
execute.

For a console app.. not sure if there one such, my expertise is limited
there..sorry i cant help much.

VJ

"Zytan" <zy**********@yahoo.comwrote in message
news:11**********************@j27g2000cwj.googlegr oups.com...
If the string really can be null, that is easy to check for. You should
check that before calling the method instead of waiting for the exception.
Actually, I just do:
int result = int.Parse("0" + s);
so, nulls are handled already.

I'm concerned with s == "ABC". The data that s can be may be warped
sometimes, and this is actually a decent spot to check to ensure it is
not warped.
If you don't really need to determine the exact reason why the string
can't be converted, you can use the int.TryParse method instead. Then
you will not need any exception handling at all.
Ah, ok, thanks, Göran!

Zytan
Mar 11 '07 #6

P: n/a
yes as Goran says its better to safe, than sorry..

I agree, and thus my post. I don't want to just handle
FormatException, when int.Parse can throw 3 different exceptions.
But, int.TryParse is perfect!
but again what I gave is
unexpected situations at a global level..
Right. What I want to know is how do I handle the exceptions that may
possibly be thrown from each function that has a change of throwing.
Like, for my int.Parse, the data could be garbled, so ALL exceptions
COULD happen. For other functions, network problems could throw
exceptions. I need to therefore test them all. And I've heard
cacthing Exception is bad, since because it gets them all, it gets out
of memory exceptions, as well, which is no good.

But, your solution is the solution to what to do with those out of
memory exceptions that are not caught (since we don't catch
Exception), and then the log can be written, error report sent home,
and gracefully exit.
Also as note... each try/catch block
is expensive so try to minimze them, and check your parameters before you
execute.
Yes, thanks. In the int.Parse case, it could be anything. So,
int.TryParse is what is needed to do the check. And no exception!
For a console app.. not sure if there one such, my expertise is limited
there..sorry i cant help much.
Well, ok, I am making a windows app, but i test in console. So, your
code compiles as-is in a windows app? I will try it.

Zytan

Mar 12 '07 #7

P: n/a
main
{
AppDomain.CurrentDomain.UnhandledException+=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
Application.Run(new MyFirstForm());
}
Ok, if this is for a windows app, what is "main"? The main form's
constructor? After InitializeComponent? No it can't be, because you
are running the first form from this. Ah, it's in Program.cs! So, I
have to change this file, and add that event handler addition line, I
see.

Ok, Application.Run(new MyFirstForm()) does work here! It doesn't in
a console app. It is really System.Windows.Forms.Application. I see.
private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// The app shuts down.., you can log here..

//After log exit
Application.Exit();
}
I presume this code must also go in Program.cs?

It works! The code is run before the debugger tells me the exception
is unhandled! So, i can test it! Thanks, VJ!

Zytan

Mar 12 '07 #8

P: n/a
On Mar 11, 5:30 pm, "Zytan" <zytanlith...@yahoo.comwrote:
main
{
AppDomain.CurrentDomain.UnhandledException+=new
UnhandledExceptionEventHandler(CurrentDomain_Unhan dledException);
Application.Run(new MyFirstForm());
}

Ok, if this is for a windows app, what is "main"? The main form's
constructor? After InitializeComponent? No it can't be, because you
are running the first form from this. Ah, it's in Program.cs! So, I
have to change this file, and add that event handler addition line, I
see.
You can add the event handler anywhere, but it's best to do it as
early as possible so that the minimum amount of code runs before the
handler is hooked up.

There is also the Application.ThreadException event. I always handle
them both.

http://msdn.microsoft.com/library/de...ptiontopic.asp

Main, by the way, is the main entry point into any application,
console or WinForms. It is usually the first piece of your code that
the CLR calls, and it's usually where you set up global exception
handlers.
Ok, Application.Run(new MyFirstForm()) does work here! It doesn't in
a console app. It is really System.Windows.Forms.Application. I see.
private static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exit();
}

I presume this code must also go in Program.cs?
Well, not necessarily. For example, I have mine in a standard error
logging class, and from my Main I call something like:

ErrorLog.Instance.SetupConsoleErrorHandling();

and inside there I subscribe to the events and the ErrorLog class
contains the event handler methods. Nonetheless, that's just because I
wanted a reusable utility. You can also have the method in your main
program .cs file. Nothing wrong with that.
Finally, I would like to offer some general advice on catching
exceptions: catch only what you can handle. Or, put another way, don't
catch an exception unless you can take some substantial action
regarding it. There are other threads in this newsgroup on exception
handling... when and how to catch an exception, but I wanted to point
that out because it explains why you (almost) never catch (Exception
ex): because it's very rare that you can take some intelligent action
with any exception that could possible happen.

The exception to that rule, of course, being logging, and that's what
global exception handlers are for.

Mar 12 '07 #9

P: n/a
You can add the event handler anywhere, but it's best to do it as
early as possible so that the minimum amount of code runs before the
handler is hooked up.
Yes, so that it's set up to handle an exception even from the
initialization code you have.
There is also the Application.ThreadException event. I always handle
them both.

http://msdn.microsoft.com/library/de...ary/en-us/cpre...
Ok, I'll look into that. What are ThreadExceptions? Like when a GUI
control is attempted to be accessed by another thread?
Main, by the way, is the main entry point into any application,
console or WinForms. It is usually the first piece of your code that
the CLR calls, and it's usually where you set up global exception
handlers.
Right, I should have known that, but I didn't know where it was hidden
in the Windows app.
I presume this code must also go in Program.cs?

Well, not necessarily. For example, I have mine in a standard error
logging class, and from my Main I call something like:

ErrorLog.Instance.SetupConsoleErrorHandling();
Ok, I just placed mine elsewhere, and it works, as long as I give
Program class access to it.

Hmm, I jus tested my program with Ctrl+F5 (not F5 debug), and an
unhandled exception window pops up. It appears that my handler
doesn't run. But, it does run if I used F5 debug. Strange.
and inside there I subscribe to the events and the ErrorLog class
contains the event handler methods. Nonetheless, that's just because I
wanted a reusable utility. You can also have the method in your main
program .cs file. Nothing wrong with that.
Right, but its best to have a unit handle this that can be reused, I
agree. So, your ErrorLog class adds the handler, and hopefully this
code is run before any other code that could throw an exception.
Finally, I would like to offer some general advice on catching
exceptions: catch only what you can handle. Or, put another way, don't
catch an exception unless you can take some substantial action
regarding it. There are other threads in this newsgroup on exception
handling... when and how to catch an exception, but I wanted to point
that out because it explains why you (almost) never catch (Exception
ex): because it's very rare that you can take some intelligent action
with any exception that could possible happen.
Yes, I agree. And my main concern was exceptions for things that are
bound to happen, such as int.Parse() or dealing with network traffic,
who knows what data may be passed into these functions, or what
network errors may result. So, in these case, I do want to handle ALL
errors gracefully. But, it seemed ugly to write 5 exceptions handlers
OR catch all excpetions with catch (Exception ex). For int.Parse, I
can use int.TryParse. For networkd traffic, it really seems ok to
catch everything. It'd be different if all the possible exceptions
were under the same exception type, but they are not.
The exception to that rule, of course, being logging, and that's what
global exception handlers are for.
Right.

Zytan

Mar 13 '07 #10

P: n/a
On Mar 13, 7:53 am, "Zytan" <zytanlith...@yahoo.comwrote:
Finally, I would like to offer some general advice on catching
exceptions: catch only what you can handle. Or, put another way, don't
catch an exception unless you can take some substantial action
regarding it. There are other threads in this newsgroup on exception
handling... when and how to catch an exception, but I wanted to point
that out because it explains why you (almost) never catch (Exception
ex): because it's very rare that you can take some intelligent action
with any exception that could possible happen.

Yes, I agree. And my main concern was exceptions for things that are
bound to happen, such as int.Parse() or dealing with network traffic,
who knows what data may be passed into these functions, or what
network errors may result. So, in these case, I do want to handle ALL
errors gracefully. But, it seemed ugly to write 5 exceptions handlers
OR catch all excpetions with catch (Exception ex). For int.Parse, I
can use int.TryParse. For networkd traffic, it really seems ok to
catch everything. It'd be different if all the possible exceptions
were under the same exception type, but they are not.
With respect to something like Int.Parse, you probably want to catch
those exceptions (of course, in .NET 2.0 you would use TryParse
instead), because you can usually recover from them: assign a default
value or whatever.

Keep in mind that by the time your global exception handler is called,
your application is toast. Dead. RIP. The global exception handler is
simply your last chance to log some information before your
application is torn down. You cannot use it to, as you say, "handle
all errors gracefully".

However, you really can't write an application that handles "all
errors gracefully": how would you handle an "out of memory" exception,
for example, or a network failure? I mean, you could, but that would
be one heck of a robust application.

If you really do want to do something to gracefully recover from an
error then you need an exception handler for that. If you want to
gracefully recover _and_ log then you need to call a logging routine
from inside the exception handler. The global exception handler is for
those exceptions that your application can't handle, but you want to
record why it is that your application exploded and died.

Mar 13 '07 #11

P: n/a
With respect to something like Int.Parse, you probably want to catch
those exceptions (of course, in .NET 2.0 you would use TryParse
instead), because you can usually recover from them: assign a default
value or whatever.
Yes.
Keep in mind that by the time your global exception handler is called,
your application is toast. Dead. RIP. The global exception handler is
simply your last chance to log some information before your
application is torn down. You cannot use it to, as you say, "handle
all errors gracefully".
Yes.
However, you really can't write an application that handles "all
errors gracefully": how would you handle an "out of memory" exception,
for example, or a network failure? I mean, you could, but that would
be one heck of a robust application.
Exactly.
If you really do want to do something to gracefully recover from an
error then you need an exception handler for that. If you want to
gracefully recover _and_ log then you need to call a logging routine
from inside the exception handler. The global exception handler is for
those exceptions that your application can't handle, but you want to
record why it is that your application exploded and died.
Yes, I follow exactly. Thanks,

http://www.pluralsight.com/blogs/cra...6/13/1455.aspx
This article claims that this code catches all unhandled exceptions:

[STAThread] static void Main() {
Application.ThreadException += new
System.Threading.ThreadExceptionEventHandler(Appli cation_ThreadException);
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e) {
throw new Exception("Whoops");
}

private static void Application_ThreadException(object sender,
System.Threading.ThreadExceptionEventArgs e) {
MessageBox.Show(e.Exception.Message);
}

Note it uses
Application.ThreadException += new ...
instead of your
AppDomain.CurrentDomain.UnhandledException +=new ...

You mentioned ThreadException, but now I'm confused. Why do these
both do the same thing?

Yours appears to NOT stop the windows dialog from appearing (when run
NOT in the debugger), whereas his code will stop it from appearing.
But, when using the debugger, yours will run BEFORE the debugger grabs
it, and his will not.

Zytan

Mar 13 '07 #12

P: n/a
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose

Public Sub MySub
on error goto errhandler

CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException

I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.

What do you suggest?

Zytan

Mar 13 '07 #13

P: n/a
Zytan wrote:
Note it uses
Application.ThreadException += new ...
instead of your
AppDomain.CurrentDomain.UnhandledException +=new ...

You mentioned ThreadException, but now I'm confused. Why do these
both do the same thing?
UnhandledException catches any unhandled exception in the application,
while ThreadException only catches unhandled exceptions that occur in
Windows Forms threads.

--
Göran Andersson
_____
http://www.guffa.com
Mar 13 '07 #14

P: n/a
On Mar 13, 1:36 pm, "Todos Menos [MSFT]"
<todos_menos_m...@hotmail.comwrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose

Public Sub MySub
on error goto errhandler

CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
Well, yeah, sort of in the same way that GOTO is much less verbose
than all of this complicated for / foreach / while garbage. Don't even
get me started about all of those wordy function headers with
parameters and stuff... when you can just make everything global and
access it from anywhere. :-)

The problem with VB6 error handling is that at _any_ point in your
code, control can magically jump to your error handler subroutine
(hey, the syntax even _says_ goto), run some code, and then slip
quietly back into the control flow of your program as if nothing
happened.

Just like GOTO, it's great when it works, and a bitch to figure out
what on earth is going on when it doesn't. Like GOTO it can be used
responsibly to great effect, or horribly abused to create
incomprehensible code.

Been there, done that. I'm happier with the way things work in .NET,
thanks.

Mar 13 '07 #15

P: n/a
In my opinion, VB6 error handling was far inferior.

Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.

Besides, is it really more verbous?

This would roughly resemble the error handling in your VB6 example:

try {

} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}

This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.

Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".

Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.
Todos Menos [MSFT] wrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose

Public Sub MySub
on error goto errhandler

CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
>Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException

I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.

What do you suggest?

Zytan


--
Göran Andersson
_____
http://www.guffa.com
Mar 13 '07 #16

P: n/a
In my opinion; C# error handling sucks.

managed error handling sucks.

on error goto errhandler was and is, far superior-- in every fashion

I heard that we're removing TRY CATCH in the next version of Visual
Studio, it should be out next month

-Todos
On Mar 13, 3:06 pm, Göran Andersson <g...@guffa.comwrote:
In my opinion, VB6 error handling was far inferior.

Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.

Besides, is it really more verbous?

This would roughly resemble the error handling in your VB6 example:

try {

} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {

MessageBox.Show(ex.Message);

}

This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.

Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".

Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.

Todos Menos [MSFT] wrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException
I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.
What do you suggest?
Zytan

--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

Mar 14 '07 #17

P: n/a
you can have multiple try catch blocks with vb6 also

with managed error handling you have to reinvent the wheel.. so that
you can then 'reinvent the wheel' ad nauseum (sp?)

I'm much happier.. oh wait a second, Vista doesn't run .NET but it
does run VB6? ROFL

and btw; kid-- if you think that .NET is so sweet-- why don't u kindly
explain to me 'how I can tell what version of the framework is on this
machine X right here, underneath my desk.'

I'll bet you $10 you don't give me a good, solid answer ROFL



On Mar 13, 1:57 pm, "Bruce Wood" <brucew...@canada.comwrote:
On Mar 13, 1:36 pm, "Todos Menos [MSFT]"

<todos_menos_m...@hotmail.comwrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub

Well, yeah, sort of in the same way that GOTO is much less verbose
than all of this complicated for / foreach / while garbage. Don't even
get me started about all of those wordy function headers with
parameters and stuff... when you can just make everything global and
access it from anywhere. :-)

The problem with VB6 error handling is that at _any_ point in your
code, control can magically jump to your error handler subroutine
(hey, the syntax even _says_ goto), run some code, and then slip
quietly back into the control flow of your program as if nothing
happened.

Just like GOTO, it's great when it works, and a bitch to figure out
what on earth is going on when it doesn't. Like GOTO it can be used
responsibly to great effect, or horribly abused to create
incomprehensible code.

Been there, done that. I'm happier with the way things work in .NET,
thanks.- Hide quoted text -

- Show quoted text -

Mar 14 '07 #18

P: n/a
then learn how to program bugfree?

uh.. instead of writing pointers, write a friggin UI?

VB has had a superior interface for 15 years.. your C# crap was never
invented

-Todos


On Mar 13, 1:37 pm, Göran Andersson <g...@guffa.comwrote:
Zytan wrote:
Note it uses
Application.ThreadException += new ...
instead of your
AppDomain.CurrentDomain.UnhandledException +=new ...
You mentioned ThreadException, but now I'm confused. Why do these
both do the same thing?

UnhandledException catches any unhandled exception in the application,
while ThreadException only catches unhandled exceptions that occur in
Windows Forms threads.

--
Göran Andersson
_____http://www.guffa.com

Mar 14 '07 #19

P: n/a
try {

} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
ErrHandler:
Select Case Err.number
Case -1 to -2130000000
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub

On Mar 13, 3:06 pm, Göran Andersson <g...@guffa.comwrote:
In my opinion, VB6 error handling was far inferior.

Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.

Besides, is it really more verbous?

This would roughly resemble the error handling in your VB6 example:

try {

} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {

MessageBox.Show(ex.Message);

}

This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.

Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".

Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.

Todos Menos [MSFT] wrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException
I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.
What do you suggest?
Zytan

--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

Mar 14 '07 #20

P: n/a
Todos Menos [MSFT] wrote:
In my opinion; C# error handling sucks.

managed error handling sucks.

on error goto errhandler was and is, far superior-- in every fashion

I heard that we're removing TRY CATCH in the next version of Visual
Studio, it should be out next month
Then you are badly misinformed.
>
-Todos
On Mar 13, 3:06 pm, Göran Andersson <g...@guffa.comwrote:
>In my opinion, VB6 error handling was far inferior.

Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.

Besides, is it really more verbous?

This would roughly resemble the error handling in your VB6 example:

try {

} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {

MessageBox.Show(ex.Message);

}

This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.

Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".

Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.

Todos Menos [MSFT] wrote:
>>in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException
I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.
What do you suggest?
Zytan
--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

--
Göran Andersson
_____
http://www.guffa.com
Mar 14 '07 #21

P: n/a
Todos Menos [MSFT] wrote:
then learn how to program bugfree?
If you truely believe that it is possible to learn how to write bugfree
code, then you have long way to go until you get to be a good programmer.
>
uh.. instead of writing pointers, write a friggin UI?

VB has had a superior interface for 15 years.. your C# crap was never
invented

-Todos


On Mar 13, 1:37 pm, Göran Andersson <g...@guffa.comwrote:
>Zytan wrote:
>>Note it uses
Application.ThreadException += new ...
instead of your
AppDomain.CurrentDomain.UnhandledException +=new ...
You mentioned ThreadException, but now I'm confused. Why do these
both do the same thing?
UnhandledException catches any unhandled exception in the application,
while ThreadException only catches unhandled exceptions that occur in
Windows Forms threads.

--
Göran Andersson
_____http://www.guffa.com


--
Göran Andersson
_____
http://www.guffa.com
Mar 14 '07 #22

P: n/a
On Mar 13, 11:24 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
then learn how to program bugfree?

If you truely believe that it is possible to learn how to write bugfree
code, then you have long way to go until you get to be a good programmer.
He's not a programmer. He's an attention-starved teenager trying to
get a response--any response--to his trolling. Best to ignore him. Or
feel sorry for him. I think he needs a girlfriend.

Mar 14 '07 #23

P: n/a
bull mother fucking shit dude

it's possible to write bugfree code.
Microsoft has brainwashed you into accepting mediocrity
SERIOUSLY HERE KIDS

bugfree code is possible when you've got $60bn in cash

they just don't produce it

On Mar 13, 11:24 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
then learn how to program bugfree?

If you truely believe that it is possible to learn how to write bugfree
code, then you have long way to go until you get to be a good programmer.


uh.. instead of writing pointers, write a friggin UI?
VB has had a superior interface for 15 years.. your C# crap was never
invented
-Todos
On Mar 13, 1:37 pm, Göran Andersson <g...@guffa.comwrote:
Zytan wrote:
Note it uses
Application.ThreadException += new ...
instead of your
AppDomain.CurrentDomain.UnhandledException +=new ...
You mentioned ThreadException, but now I'm confused. Why do these
both do the same thing?
UnhandledException catches any unhandled exception in the application,
while ThreadException only catches unhandled exceptions that occur in
Windows Forms threads.
--
Göran Andersson
_____http://www.guffa.com

--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

Mar 14 '07 #24

P: n/a
I'm not misinformed.

I'm not the one that's using the trendy 'programming language of the
month'

just because C and Java had a MOTHER FUCKING _CRAP_ GUI for the past
10 years.. does that mean you should hop on the first language that's
competitive with VB?

VB won the war kid

Java -- I mean get real, Sun is worth what.. $3bn? PHP has 4 times the
following of Java..



On Mar 13, 11:09 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
In my opinion; C# error handling sucks.
managed error handling sucks.
on error goto errhandler was and is, far superior-- in every fashion
I heard that we're removing TRY CATCH in the next version of Visual
Studio, it should be out next month

Then you are badly misinformed.


-Todos
On Mar 13, 3:06 pm, Göran Andersson <g...@guffa.comwrote:
In my opinion, VB6 error handling was far inferior.
Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.
Besides, is it really more verbous?
This would roughly resemble the error handling in your VB6 example:
try {
} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.
Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".
Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.
Todos Menos [MSFT] wrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException
I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.
What do you suggest?
Zytan
--
Göran Andersson
_____http://www.guffa.com-Hide quoted text -
- Show quoted text -

--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

Mar 14 '07 #25

P: n/a
I'm not mis-informed
i just don't accept VERBOSITY laying down

your try catch crap.. I mean seriously here.. what a waste of keyboard
effort

On Mar 13, 11:09 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
In my opinion; C# error handling sucks.
managed error handling sucks.
on error goto errhandler was and is, far superior-- in every fashion
I heard that we're removing TRY CATCH in the next version of Visual
Studio, it should be out next month

Then you are badly misinformed.


-Todos
On Mar 13, 3:06 pm, Göran Andersson <g...@guffa.comwrote:
In my opinion, VB6 error handling was far inferior.
Shorter code is not always better code. What's difficult about
programming is not typing in the commands, so how much you have to type
has little impact on the efficiency of a programmer.
Besides, is it really more verbous?
This would roughly resemble the error handling in your VB6 example:
try {
} catch (IOException) {
} catch (FormatException) {
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
This is 108 characters compared to 158 (not counting tabs and line
breaks). Unless I have forgotten most of my math, that is much less, not
much more.
Handling different error types is built into the exception model, while
in VB6 you have to use a Select Case to determine the error type. Also
"IOException" says a lot more than "12345".
Exception handling fits well into the structure of the code, while in
VB6 error handling you have to jump back and forth in the code.
Spaghetti code is always harder to follow.
Todos Menos [MSFT] wrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub
On Mar 10, 3:46 pm, "Zytan" <zytanlith...@yahoo.comwrote:
Ok something simple like int.Parse(string) can throw these exceptions:
ArgumentNullException, FormatException, OverflowException
I don't want my program to just crash on an exception, so I must
handle all of them. I don't care about which one happened, except to
write out exception.Message to a log file. It seems verbose to write
out three handlers that all do the same thing. So, I could just catch
Exception. But, is that recommended? It'll catch everything, even
out of memory exceptions.
What do you suggest?
Zytan
--
Göran Andersson
_____http://www.guffa.com-Hide quoted text -
- Show quoted text -

--
Göran Andersson
_____http://www.guffa.com- Hide quoted text -

- Show quoted text -

Mar 14 '07 #26

P: n/a
re: and a bitch to figure out
what on earth is going on when it doesn't.

oh does the widdle baby programmer have a hard time following a widdle
goto statement

oh how cute

IT IS A GOTO STATEMENT DUDE. HOW MUCH SIMPLER CAN YOU GET?
On Mar 13, 1:57 pm, "Bruce Wood" <brucew...@canada.comwrote:
On Mar 13, 1:36 pm, "Todos Menos [MSFT]"

<todos_menos_m...@hotmail.comwrote:
in my opinion, vb6 error handler was much superior than this managed
crap.. i mean seriously-- it's a lot less verbose
Public Sub MySub
on error goto errhandler
CleanExit:
exit sub
ErrHandler:
Select Case Err.number
Case 12345, 1224334
resume cleanexit
case else
msgbox error$
resume cleanexit
end Select
End Sub

Well, yeah, sort of in the same way that GOTO is much less verbose
than all of this complicated for / foreach / while garbage. Don't even
get me started about all of those wordy function headers with
parameters and stuff... when you can just make everything global and
access it from anywhere. :-)

The problem with VB6 error handling is that at _any_ point in your
code, control can magically jump to your error handler subroutine
(hey, the syntax even _says_ goto), run some code, and then slip
quietly back into the control flow of your program as if nothing
happened.

Just like GOTO, it's great when it works, and a bitch to figure out
what on earth is going on when it doesn't. Like GOTO it can be used
responsibly to great effect, or horribly abused to create
incomprehensible code.

Been there, done that. I'm happier with the way things work in .NET,
thanks.- Hide quoted text -

- Show quoted text -

Mar 14 '07 #27

P: n/a
First off,

We should try and avoid exceptions where possible

And as far as int parsing try something like this

#region isInteger
/// <summary>
/// Determines if it is a valid integer.
/// </summary>
/// <param name="var"></param>
/// <returns></returns>
public static bool isInteger(string var)
{
double result;

return (Double.TryParse(var,
System.Globalization.NumberStyles.Integer,
System.Globalization.NumberFormatInfo.CurrentInfo,
out result));
}
#endregion

#region -- intFromString --
/// <summary>
/// Safely casts a string as integer. If the string is not a valid
int NOT_INITIALISED_INT is returned.
/// </summary>
/// <param name="var">string to attempt parse on</param>
/// <param name="iDefault">int - Default to use if the string is not
a valid int</param>
/// <returns>int</returns>
public static int intFromString( string var )
{
return intFromString( var, NOT_INITIALISED_INT );
}

/// <summary>
/// Safely casts a string as integer. If the string is not a valid
int the default value is used.
/// </summary>
/// <param name="var">string to attempt parse on</param>
/// <param name="iDefault">int - Default to use if the string is not
a valid int</param>
/// <returns>int</returns>
public static int intFromString( string var, int iDefault )
{
if( isInteger( var ) )
{
return int.Parse( var );
}

return iDefault;
}
#endregion

That should get you by safely.
And if you care to test that over 100k iterations against a try catch
you will see why it is worth the effort.

On the error handling front,
In a web application we use a HttpModule with a configurable level of
reporting

This allows us to essential switch it up to maximum reporting level
during the first phase of deployment.
This is obviously slower and puts a greater load on the server, but
allows us to track and remove bugs.

This is only my opinion
After 10 years of developing commercial systems that interact with 3rd
parties I have to say that exceptions
are unavoidable but predictable. You should not be looking to trap
developer errors, these should be caught and fixed during
UAT ( this also goes if you are writing libray code for other
people ).
Rather you should be looking to cater for errors in comms failure
between your external interfaces and 3rd party software
(this includes importing files )

Hope this helps

Mar 14 '07 #28

P: n/a
re:
Also as note... each try/catch block
is expensive so try to minimze them, and check your parameters before
you
execute.
yeah you're right

if Microsoft gave a damn about performance they never would have
invented .NET

On Mar 11, 7:23 am, "VJ" <nonewsaddr...@yahoo.comwrote:
yes as Goran says its better to safe, than sorry.. but again what I gave is
unexpected situations at a global level.. That is provided by the .NET
environment, for windows applications. Also as note... each try/catch block
is expensive so try to minimze them, and check your parameters before you
execute.

For a console app.. not sure if there one such, my expertise is limited
there..sorry i cant help much.

VJ

"Zytan" <zytanlith...@yahoo.comwrote in message

news:11**********************@j27g2000cwj.googlegr oups.com...
If the string really can be null, that is easy to check for. You should
check that before calling the method instead of waiting for the exception.

Actually, I just do:
int result = int.Parse("0" + s);
so, nulls are handled already.

I'm concerned with s == "ABC". The data that s can be may be warped
sometimes, and this is actually a decent spot to check to ensure it is
not warped.
If you don't really need to determine the exact reason why the string
can't be converted, you can use the int.TryParse method instead. Then
you will not need any exception handling at all.

Ah, ok, thanks, Göran!

Zytan

Mar 14 '07 #29

P: n/a
VJ <no***********@yahoo.comwrote:
yes as Goran says its better to safe, than sorry.. but again what I gave is
unexpected situations at a global level.. That is provided by the .NET
environment, for windows applications. Also as note... each try/catch block
is expensive so try to minimze them, and check your parameters before you
execute.
try/catch blocks aren't expensive - it's only when exceptions are
*thrown* that there's any significant expense. Even that expense is
generally vastly overestimated by most people.

It's good practice to check parameters anyway, as then the *exact*
reason is apparent, and you can make sure that you don't "half"
complete an action. However, the correct response to incorrect
parameters is usually to throw an exception anyway...

See http://pobox.com/~skeet/csharp/exceptions.html and
http://pobox.com/~skeet/csharp/exceptions2.html
for more information.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 14 '07 #30

P: n/a
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET
It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.

--
Göran Andersson
_____
http://www.guffa.com
Mar 15 '07 #31

P: n/a
Göran Andersson wrote:
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET

It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.
Don't feed the trolls!

-- Barry

--
http://barrkel.blogspot.com/
Mar 15 '07 #32

P: n/a
Göran Andersson <gu***@guffa.comwrote:
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET
It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.
That's rubbish. Java and .NET generally perform roughly equivalently.
Java has been in the same ballpark as native code (eg 0-20% slower) for
quite a long time, so unless you're suggesting that .NET runs 2-3 times
faster than native code...

There are certainly areas where .NET outperforms Java. There are areas
where Java outperforms .NET. However, you'd have to pick an area where
Java is *really, really* poor and make that the bottleneck to get a 2-3
times speed improvement by using .NET.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 15 '07 #33

P: n/a
Bruce

whatever kid
I just don't accept mediocrity.
I don't accept an IDE that takes 120 seconds to open up.. on a core 2
duo laptop

sue me-- I just know that Microsoft can do BETTER

they did do BETTER-- it is called VB6

with Vb6 I could use one code base for clientside DHTML, server side
ASP; DTS; Excel, Outlook, Access and VBS.

Can VB.net do _ANY_ of those things?

I mean-- get real buddy

On Mar 13, 11:43 pm, "Bruce Wood" <brucew...@canada.comwrote:
On Mar 13, 11:24 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
then learn how to program bugfree?
If you truely believe that it is possible to learn how to write bugfree
code, then you have long way to go until you get to be a good programmer.

He's not a programmer. He's an attention-starved teenager trying to
get a response--any response--to his trolling. Best to ignore him. Or
feel sorry for him. I think he needs a girlfriend.

Mar 15 '07 #34

P: n/a
Jon Skeet [C# MVP] wrote:
Göran Andersson <gu***@guffa.comwrote:
>Todos Menos [MSFT] wrote:
>>if Microsoft gave a damn about performance they never would have
invented .NET
It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.

That's rubbish. Java and .NET generally perform roughly equivalently.
Java has been in the same ballpark as native code (eg 0-20% slower) for
quite a long time, so unless you're suggesting that .NET runs 2-3 times
faster than native code...

There are certainly areas where .NET outperforms Java. There are areas
where Java outperforms .NET. However, you'd have to pick an area where
Java is *really, really* poor and make that the bottleneck to get a 2-3
times speed improvement by using .NET.
Perhaps it's rubbish. I based my statement on these tests:
http://dada.perl.it/shootout/

In all the tests that I looked at, except exception handing, C# was 2-3
times faster than Java.

I see now that it's been a while since the last update, so newer
versions of Java might perform much better. I know that never versions
of C# performs better.

--
Göran Andersson
_____
http://www.guffa.com
Mar 15 '07 #35

P: n/a
who gives a crap about Java! they're a $3 billion market cap.. Atari
could buy Sun!

Microsoft had the msot popular language in the world; they killed it.
FOR NO REASON. WITHOUT A REPLACEMENT.

AND THIS SEE-SHARP CRAP? it was never invented!
AND THIS SEE-SHARP CRAP? it was never invented!
AND THIS SEE-SHARP CRAP? it was never invented!

On Mar 14, 5:20 pm, Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET

It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.

--
Göran Andersson
_____http://www.guffa.com

Mar 15 '07 #36

P: n/a
they sold us car that is incompatible with existing highways!

it doesn't 'go faster' it isn't compatible

I've never had a performance problem with Vb6.. why in the hell would
they make US change langauges?

you guys are the dipshits that bet on the wrong team. Java is dead; it
always has been. VB won the war.

C# is for wimps that are too trendy to use a real language
just because C has had a _CRAP_ interface for a decade-- does this
mean that VB goes away as soon as C gets a decent interface?

ROFL

C# is for kids; MS didn't need a 'kids programming language'

VB works in DTS, Clientside DHTML-- when you guys can run C# on the
clientside is when your langauge has a leg to stand on

as it is; I can cut and paste code between DHTML, ASP, Excel, Access,
Outlook, VBS

can C# do _ANY_ of those thigns?

Why would I want to use 5 languages when ONE works just fine

TAKE THIS LANGUAGE AND SHOVE IT!
On Mar 15, 12:08 am, Jon Skeet [C# MVP] <s...@pobox.comwrote:
Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET
It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.

That's rubbish. Java and .NET generally perform roughly equivalently.
Java has been in the same ballpark as native code (eg 0-20% slower) for
quite a long time, so unless you're suggesting that .NET runs 2-3 times
faster than native code...

There are certainly areas where .NET outperforms Java. There are areas
where Java outperforms .NET. However, you'd have to pick an area where
Java is *really, really* poor and make that the bottleneck to get a 2-3
times speed improvement by using .NET.

--
Jon Skeet - <s...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 15 '07 #37

P: n/a
Java and .NET both run to slow IN DEVELOPMENT because neither is
compatible with Vb6

On Mar 15, 12:08 am, Jon Skeet [C# MVP] <s...@pobox.comwrote:
Göran Andersson <g...@guffa.comwrote:
Todos Menos [MSFT] wrote:
if Microsoft gave a damn about performance they never would have
invented .NET
It's true that object oriented languages are not primarily targeted on
speed, but C# performs quite well never the less. It's for example
generally 2-3 times faster than Java.

That's rubbish. Java and .NET generally perform roughly equivalently.
Java has been in the same ballpark as native code (eg 0-20% slower) for
quite a long time, so unless you're suggesting that .NET runs 2-3 times
faster than native code...

There are certainly areas where .NET outperforms Java. There are areas
where Java outperforms .NET. However, you'd have to pick an area where
Java is *really, really* poor and make that the bottleneck to get a 2-3
times speed improvement by using .NET.

--
Jon Skeet - <s...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Mar 15 '07 #38

P: n/a
Göran Andersson <gu***@guffa.comwrote:

<snip>
Perhaps it's rubbish. I based my statement on these tests:
http://dada.perl.it/shootout/

In all the tests that I looked at, except exception handing, C# was 2-3
times faster than Java.

I see now that it's been a while since the last update, so newer
versions of Java might perform much better. I know that never versions
of C# performs better.
The code shown doesn't show the loops being timed, so my guess is that
it's the *total* CPU time for the whole program.

One area where Java certainly *is* worse is startup time. If that's
being included in the total time, then the results are a farce - most
programs *don't* run for subsecond times.

It also doesn't appear to allow for JIT warmup, which again would bias
things massively.

Of course, if the methodology page were up, we'd have some more idea
about this...

I'll have a go at putting some of the code provided into a more
reasonable benchmarking framework, and we'll see what the results are.
Java certainly *isn't* 2-3 times slower than C# - but there are some
*very* bad benchmarks out there.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 15 '07 #39

P: n/a
Jon Skeet [C# MVP] <sk***@pobox.comwrote:

<snip>
I'll have a go at putting some of the code provided into a more
reasonable benchmarking framework, and we'll see what the results are.
Java certainly *isn't* 2-3 times slower than C# - but there are some
*very* bad benchmarks out there.
Okay, I've got the nested loop test in a better shape. This one showed
CPU of 0.28 for C# and 0.85 for Java on the web page, so C# appears to
be three times faster, right? Well, let's try a more balanced test...

Java code:
public class NestedLoop
{
public static void main(String[] args)
{
int iterations = Integer.parseInt(args[0]);
int loop = Integer.parseInt(args[1]);

long total = 0;
long start = System.currentTimeMillis();
for (int i=0; i < iterations; i++)
{
total += test(loop);
}
long end = System.currentTimeMillis();
System.out.println ("Total time (ms): "+(end-start));
System.out.println ("Running total: "+total);
}

public static int test(int n)
{
int x=0;
for (int a=0; a<n; a++)
for (int b=0; b<n; b++)
for (int c=0; c<n; c++)
for (int d=0; d<n; d++)
for (int e=0; e<n; e++)
for (int f=0; f<n; f++)
x++;
return x;
}
}

C# code:
using System;

public class NestedLoop
{
public static void Main(string[] args)
{
int iterations = int.Parse(args[0]);
int loop = int.Parse(args[1]);

long total = 0;
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
total += Test(loop);
}
DateTime end = DateTime.Now;
Console.WriteLine ("Total time (ms): "+
(end-start).TotalMilliseconds);
Console.WriteLine ("Running total: "+total);
}

public static int Test(int n)
{
int x=0;
for (int a=0; a<n; a++)
for (int b=0; b<n; b++)
for (int c=0; c<n; c++)
for (int d=0; d<n; d++)
for (int e=0; e<n; e++)
for (int f=0; f<n; f++)
x++;
return x;
}
}
Points to note:
1) My results are taken given suitably large numbers, so that the Java
JIT has time to "warm up" (i.e. re-optimise), and so that timing
granularity is irrelevant (so it doesn't matter that I'm not using
StopWatch in .NET).

2) We're only testing the time take to do the actual looping (and
method call) rather than including the startup time (which I believe to
be the main cause of bias in the web results)

3) We're measuring elapsed time rather than CPU time. However, the
tests were conducted on an idle box (admittedly Vista, which is never
completely idle!) and shot up to 100% during the tests - I don't think
the difference would be significant.

So, results on my laptop (C# 2, .NET 3, Java 1.6):

C:\Users\Jon\Test>java NestedLoop 1000 15
Total time (ms): 27188
Running total: 11390625000

C:\Users\Jon\Test>nestedloop 1000 15
Total time (ms): 37154.8485
Running total: 11390625000

In other words, C#: 37s, Java: 27s.
Instead of Java being shown to be 3 times *slower* in this test, it's
actually 25% faster.

I don't plan to repeat this for all the other tests on the web page,
but hopefully that shows you just how much stock you should put in
their testing methodology.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 15 '07 #40

P: n/a
It seems verbose to write
out three handlers that all do the same thing. So, I could just catchException. But, is that recommended? It'll catch everything, even
out of memory exceptions.
http://blogs.msdn.com/brada/archive/...04/385531.aspx
Effective .NET Framework based development: Exception handing and
Memory Management

Brad Abrams states:

"catch (Exception e) is your friend

Myth: Catching Exception is evil
This is motivated by a desire to avoid catching low level exceptions
such as OutOfMemoryException, and StackOverflowException

Do catch every exception you should handle

Don't attempt to catch every exception a method could throw
Its ugly, version brittle, and difficult to test

Catch what you need to handle, let the rest pass"

Zytan

Mar 31 '07 #41

P: n/a
on error goto worked better in my opinion

I mean; using a simple select case statement; you could trap RANGES of
errors

this isn't possible using .NET
'yeah lets just identify every possible error and write it out by
hand'

what a stupid language

LONG LIVE VB6; it's still more popular than VB.net _AND_ C# combined!~

On Mar 30, 7:11 pm, "Zytan" <zytanlith...@gmail.comwrote:
It seems verbose to write
out three handlers that all do the same thing. So, I could just catchException. But, is that recommended? It'll catch everything, even
out of memory exceptions.

http://blogs.msdn.com/brada/archive/...04/385531.aspx
Effective .NET Framework based development: Exception handing and
Memory Management

Brad Abrams states:

"catch (Exception e) is your friend

Myth: Catching Exception is evil
This is motivated by a desire to avoid catching low level exceptions
such as OutOfMemoryException, and StackOverflowException

Do catch every exception you should handle

Don't attempt to catch every exception a method could throw
Its ugly, version brittle, and difficult to test

Catch what you need to handle, let the rest pass"

Zytan

Apr 2 '07 #42

This discussion thread is closed

Replies have been disabled for this discussion.