473,766 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception handling suggestions

Ok something simple like int.Parse(strin g) can throw these exceptions:
ArgumentNullExc eption, FormatException , OverflowExcepti on

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.Messa ge 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
41 3070
VJ
main
{
AppDomain.Curre ntDomain.Unhand ledException+=n ew
UnhandledExcept ionEventHandler (CurrentDomain_ UnhandledExcept ion);
Application.Run (new MyFirstForm());
}

private static void CurrentDomain_U nhandledExcepti on(object sender,
UnhandledExcept ionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exi t();

}

That should take care of it..
VJ

"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ q40g2000cwq.goo glegroups.com.. .
Ok something simple like int.Parse(strin g) can throw these exceptions:
ArgumentNullExc eption, FormatException , OverflowExcepti on

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.Messa ge 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
main
{
AppDomain.Curre ntDomain.Unhand ledException+=n ew
UnhandledExcept ionEventHandler (CurrentDomain_ UnhandledExcept ion);
Application.Run (new MyFirstForm());
}

private static void CurrentDomain_U nhandledExcepti on(object sender,
UnhandledExcept ionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exi t();
}
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
Zytan wrote:
Ok something simple like int.Parse(strin g) can throw these exceptions:
ArgumentNullExc eption, FormatException , OverflowExcepti on

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.Messa ge 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
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
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**********@y ahoo.comwrote in message
news:11******** **************@ j27g2000cwj.goo glegroups.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
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
main
{
AppDomain.Curre ntDomain.Unhand ledException+=n ew
UnhandledExcept ionEventHandler (CurrentDomain_ UnhandledExcept ion);
Application.Run (new MyFirstForm());
}
Ok, if this is for a windows app, what is "main"? The main form's
constructor? After InitializeCompo nent? 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.Applicati on. I see.
private static void CurrentDomain_U nhandledExcepti on(object sender,
UnhandledExcept ionEventArgs e)
{
// The app shuts down.., you can log here..

//After log exit
Application.Exi t();
}
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
On Mar 11, 5:30 pm, "Zytan" <zytanlith...@y ahoo.comwrote:
main
{
AppDomain.Curre ntDomain.Unhand ledException+=n ew
UnhandledExcept ionEventHandler (CurrentDomain_ UnhandledExcept ion);
Application.Run (new MyFirstForm());
}

Ok, if this is for a windows app, what is "main"? The main form's
constructor? After InitializeCompo nent? 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.Thr eadException 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.Applicati on. I see.
private static void CurrentDomain_U nhandledExcepti on(object sender,
UnhandledExcept ionEventArgs e)
{
// The app shuts down.., you can log here..
//After log exit
Application.Exi t();
}

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.Instan ce.SetupConsole ErrorHandling() ;

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
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.Thr eadException event. I always handle
them both.

http://msdn.microsoft.com/library/de...ary/en-us/cpre...
Ok, I'll look into that. What are ThreadException s? 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.Instan ce.SetupConsole ErrorHandling() ;
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

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

Similar topics

4
3136
by: zzfreddybb | last post by:
We are using HP aCC compiler on a HP Itanium box ( 11.23) We are having some severe performance hits using exception handling ( try/catch ) scenarios. The online aCC documentation says: HP aC++ exception handling has no significant performance impact at compile-time or run-time. We have not found this to be the case at all.
11
3273
by: Master of C++ | last post by:
Hi, I am writing a simulation package in C++, and so far I've written about 8000 lines of code and have about 30 classes. I haven't used C++ exceptions so far (for various reasons). The only two "resources" I use are memory and file I/O and whenever there is a memory allocation failure or file I/O failure I just simply call a custom assert-type function to check, print a error message and abort. This seems to be OK for now (for the...
6
1904
by: Josh Mcfarlane | last post by:
I keep trying to get myself out of the return-code mindset, but it doesn't seem to work. They are suppose to get rid of if-then statements of return codes, but you still have to do an if statement once the code leaves your control (3rd party libraries, OS functions, etc) to throw an exception? Does anyone have any good suggestions on a book or website that deals with exception handling that could help turn this poor mind off of return...
7
1798
by: Dan Bass | last post by:
In a somewhat complex application, I've developed plug-in architecture and am having a problem as to when to catch general exceptions for logging purposes. In each plug-in class library, for example, I'm assuming it's throw on errors, and that the core then catches them. I've got proxy classes handling some fiddly details of the plug-ins. Should I allow the exception to bubble to the top most point it can in a call stack, then catch...
11
5600
by: chopsnsauce | last post by:
Here's the example: Dim frm As New FORM1 Try frm.show Catch ex As Exception msgbox ex.message
2
2990
by: Petr Jakes | last post by:
I am a little bit confused by all possibilities for exceptions handling in Python (probably because I am not skilled enough??) I did try to search trough this list and reading Python tutorial about Errors and Exceptions but didn't find some "general" answer about exception handling policy (strategy). In the following example each row can IMHO raise an exception (if the Firebird service is not running for example, if the database is...
1
338
by: Yoav | last post by:
Hi, I have a web application in which I have implemented exception handling – my own custom exception etc. My question is - what do I do with exceptions in the Global.asax event? I don't want to redirect users to an error page - I want to keep unity in my exception handling (I don't do it for other exceptions). Any suggestions? Thanks
2
4045
by: jayapal | last post by:
Hi , I am using the NEW operator to allocate the memory in many places of my code.But I am not doing any error hadling or exception handling.Can any one suggests me how to do exception handling, which code part I have to add to do the exception handling Thanks in advance, ..
6
4397
by: Steve | last post by:
Hi All I have a windows forms Application (SAM) in vb.net 2008 using .net framework V2 One and only one customer out of 30 customers is getting errors daily where they have to close and restart my application, sometimes several times a day The customer has XP Home SP2
0
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8835
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.