473,657 Members | 2,845 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

.Net Exceptions

Is there any way to find out if a particular .net function will throw an
exception without first generating the exception?

I am using structured exception handling i.e. try catch finally blocks with
a top level catch all for Exception. However, I would like to be able to
catch most .net exceptions when they are generated. I would then be able to
generate a valuable exception message and do something about it!!! Hence the
question above.

If anyone would like to talk about their preferred exception handling
methodology I am all ears.

Thanks,
Mark
Jul 21 '05 #1
24 2487
Hi mag31,

To my knowledge, unless the exception is documented somewhere, or you have access to the original source to see what exceptions that method may throw, you have to resort to a general exception catching, catch(Exception ex).

--
Happy Coding!
Morten Wennevik [C# MVP]
Jul 21 '05 #2
Thank you Morten, that answers my question, obviously not with the answer I
want :-(

Mark

"Morten Wennevik" wrote:
Hi mag31,

To my knowledge, unless the exception is documented somewhere, or you have access to the original source to see what exceptions that method may throw, you have to resort to a general exception catching, catch(Exception ex).

--
Happy Coding!
Morten Wennevik [C# MVP]

Jul 21 '05 #3
Imho, .NET has a very stupid exception model. There is not way telling which
exceptions can be thrown by a specifiy method. Also the Exception hirarchy
seems not to be well designed.

Lots of people keep telling you that using catch (Exception) is bad style
and you should always catch specific exception Iam the opinion that in some
places is the the best method. Especially when calling third party
components or wrapped winapi stuff like Process.Start or creating Database
connections, you never know which kind of exception can be thrown.
Even if exceptions are documented there a chance that something was
forgotten to document or in a later version a new exception is thrown in
that component or maybe you forget to catch one specific exception.

Sure, if you call int.Parse() you will certainly only catch FormatException
or when reading from a file there will nothing else be thrown except
IOException. But as I said sometimes its better to catch System.Exceptio n,
just to be sure.

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
"mag31" <ma***@discussi ons.microsoft.c om> schrieb im Newsbeitrag
news:F2******** *************** ***********@mic rosoft.com...
Is there any way to find out if a particular .net function will throw an
exception without first generating the exception?

I am using structured exception handling i.e. try catch finally blocks with a top level catch all for Exception. However, I would like to be able to
catch most .net exceptions when they are generated. I would then be able to generate a valuable exception message and do something about it!!! Hence the question above.

If anyone would like to talk about their preferred exception handling
methodology I am all ears.

Thanks,
Mark

Jul 21 '05 #4
cody wrote:
Imho, .NET has a very stupid exception model. There is not way
telling which exceptions can be thrown by a specifiy method. Also the
Exception hirarchy seems not to be well designed.
I disagree on the model part, but regarding the hierarchy you're right.
What's really missing is a distinction between potentially recoverable
conditions and irrecoverable failures -- lo and behold, that's what
Exception and Error in Java represent. In defense of MS, getting an
excpetion hierarchy right is incredibly hard -- but since they borrowed so
many good things from Java, they should taken that part as well ;-)

And this is not the same as the SystemException vs. ApplicationExce ption
approach, which doesn't cut it anyway.
Lots of people keep telling you that using catch (Exception) is bad
style and you should always catch specific exception Iam the opinion
that in some places is the the best method.
No. When you say catch (Exception) you think it means:

"This stupid API isn't properly documented, so I need to be sure."

But what it means is

"I can handle it."

Unfortunately, nothing could more mistaken. Depending on the failure, you
may hide or swallow a severe problem. Of course that's caused by the missing
distinction between Error and Exception. But save for a global "log and
die/abort" exception handler, there's little you can do with catch
(Exception).
Especially when calling
third party components or wrapped winapi stuff like Process.Start or
creating Database connections, you never know which kind of exception
can be thrown.
Can you give an example?
Even if exceptions are documented there a chance that something was
forgotten to document or in a later version a new exception is thrown
in that component or maybe you forget to catch one specific exception.
First, hopefully nobody drops an updated library in production without prior
testing. Grab the library, run your unit tests (which hopefully cover both
normal and exptected error conditions), and check the green light. If your
development process doesn't include this very basic step, you're in trouble
anyway...
Sure, if you call int.Parse() you will certainly only catch
FormatException or when reading from a file there will nothing else
be thrown except IOException. But as I said sometimes its better to
catch System.Exceptio n, just to be sure.


To be sure of what ;-)

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Jul 21 '05 #5
> > Imho, .NET has a very stupid exception model. There is not way
telling which exceptions can be thrown by a specifiy method. Also the
Exception hirarchy seems not to be well designed.
I disagree on the model part, but regarding the hierarchy you're right.
What's really missing is a distinction between potentially recoverable
conditions and irrecoverable failures -- lo and behold, that's what
Exception and Error in Java represent. In defense of MS, getting an
excpetion hierarchy right is incredibly hard -- but since they borrowed so
many good things from Java, they should taken that part as well ;-)

And this is not the same as the SystemException vs. ApplicationExce ption
approach, which doesn't cut it anyway.
Lots of people keep telling you that using catch (Exception) is bad
style and you should always catch specific exception Iam the opinion
that in some places is the the best method.


No. When you say catch (Exception) you think it means:

"This stupid API isn't properly documented, so I need to be sure."

But what it means is

"I can handle it."


Yes indeed. If I try to start a process with Process.Start() and an
exception occures who cares what kind of error it was? I display a
messagebox and inform the user what happens and display the message from the
exception.
The same is true when trying to open a Database connection or calling a
method which loads a specific file.
The most stupid thing one could do is to catch every exception type that
could possibly occur in an endless stack of catch clauses, each of them
doing the same thing: informing the user and displaying the message of the
exception.
And at the end, an undocumented exception occures which never occured during
testing because it occures because of a wrong driver or similar and this
lets the whole application crash, just because you were soo sure that only
the documented exceptions could occur..
Unfortunately, nothing could more mistaken. Depending on the failure, you
may hide or swallow a severe problem. Of course that's caused by the missing distinction between Error and Exception. But save for a global "log and
die/abort" exception handler, there's little you can do with catch
(Exception).
Especially when calling
third party components or wrapped winapi stuff like Process.Start or
creating Database connections, you never know which kind of exception
can be thrown.


Can you give an example?


You would let your application totally crash just because you third party
sound library throws a funny exception when you tried to play background
sound but the user does have funny hardware which lets the soundcomponent
totally crash. Will you really trust every third party component? You never
should.
Nobody cares wheather the stupid background sounds works or not. But if your
programm crashes because of that you're the stupid.

We *can* trust our own code, sure. But we cannot trust 3rd party components
as we do not have their sourcecode.

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Jul 21 '05 #6
> I disagree on the model part, but regarding the hierarchy you're right.
What's really missing is a distinction between potentially recoverable
conditions and irrecoverable failures -- lo and behold, that's what
Exception and Error in Java represent.
It isn't at all clear to me how a component that throws an exception can
determine if something is recoverable or not - perhaps there are times it
can, but there are more cases where only a higher-level module can make that
decision.
And this is not the same as the SystemException vs. ApplicationExce ption
approach, which doesn't cut it anyway.
Agreed. On the surface it would be useful to have categories such as
SystemFatalExce ption, SystemCriticalE xception, but then this opens a
different can of worms - the ability to recover or not from an exception is
application dependent unless the runtime has become corrupted and is about
to shutdown.
No. When you say catch (Exception) you think it means:

"This stupid API isn't properly documented, so I need to be sure."

But what it means is

"I can handle it."

Unfortunately, nothing could more mistaken. Depending on the failure, you
may hide or swallow a severe problem. Of course that's caused by the missing distinction between Error and Exception. But save for a global "log and
die/abort" exception handler, there's little you can do with catch
(Exception).

I have come to use something like this...

catch(SomeSpeci ficException sse)
{
// recover/retry/whatever
}
catch(Exception ex)
{
throw new CloneExceptionT ype(ex,"Add some context info here."); // or
throw some other type
}

....and kick it upstairs for high-level code to deal with. Ultimately it
boils down to 2 basic choices - either the code knows how to recover from an
exception or it doesn't. If it doesn't, then you can either allow the user
to retry/cancel/abort the operation, or you can exit the application.


First, hopefully nobody drops an updated library in production without prior testing. Grab the library, run your unit tests (which hopefully cover both
normal and exptected error conditions), and check the green light. If your
development process doesn't include this very basic step, you're in trouble anyway...


I kind of disagree here; I use unit testing and it is a valuable
tool/technique but sometimes all it does is validate our own misconceptions.
It will not force a third-party component to throw exceptions, especially
ones that you did not know could be thrown - if it did then you are really
writing a unit test that validates the component, not your own code. A unit
test would probably create a mock object for the library/component. I think
testing an external component used by your code is more of a systems test
then a unit test.

One problem is how a system evolves over time. Even if you nail it and
handle every specific exception in the original code base, as it evolves and
as components change there is no way to prevent them from throwing exception
types different then those thrown in the original implementation. A robust
system must have some way of dealing with new/unexpected error conditions,
and this forces it to catch and deal with the generic Exception type.

Jul 21 '05 #7
cody wrote:
Lots of people keep telling you that using catch (Exception) is bad
style and you should always catch specific exception Iam the opinion
that in some places is the the best method.
No. When you say catch (Exception) you think it means:

"This stupid API isn't properly documented, so I need to be sure."

But what it means is

"I can handle it."


Yes indeed. If I try to start a process with Process.Start() and an
exception occures who cares what kind of error it was? I display a
messagebox and inform the user what happens and display the message
from the exception.


Which depending on the exception may not work.
The same is true when trying to open a Database connection or calling
a method which loads a specific file.
The most stupid thing one could do is to catch every exception type
that could possibly occur in an endless stack of catch clauses, each
of them doing the same thing: informing the user and displaying the
message of the exception.
And at the end, an undocumented exception occures which never occured
during testing because it occures because of a wrong driver or
similar and this lets the whole application crash, just because you
were soo sure that only the documented exceptions could occur..
Again, you're assuming that this is recoverable situation. But in truth, you
don't know if an unexpected exception is recoverable. Also, I don't see the
benefit of an error message saying: "Oops. Dunno what happened, but we'll
continue for now. Stay tuned." A better approach to me is
terminate-and-restart, like the way newer MS Office applications behave.
Unfortunately, nothing could more mistaken. Depending on the
failure, you may hide or swallow a severe problem. Of course that's
caused by the missing distinction between Error and Exception. But
save for a global "log and die/abort" exception handler, there's
little you can do with catch (Exception).
Especially when calling
third party components or wrapped winapi stuff like Process.Start or
creating Database connections, you never know which kind of
exception can be thrown.


Can you give an example?


You would let your application totally crash just because you third
party sound library throws a funny exception when you tried to play
background sound but the user does have funny hardware which lets the
soundcomponent totally crash. Will you really trust every third party
component? You never should.


Again, you only know that *afterwards*, when analyzing a stacktrace. At
runtime, all you can do is keep fingers crossed. A third party library
should not throw "funny" exceptions, but expose a properly designed
exception hierarchy -- otherwise it may do more harm than good.

[...] We *can* trust our own code, sure. But we cannot trust 3rd party
components as we do not have their sourcecode.


That's probably the propert way to look at it from a security perspective,
but from an OO point of view that won't work. Either an exception is part of
a component's accessible API or not. If not, it is an implementation detail
you should not deal with. And can we trust our own code? No. Even our own
code can throw way more exceptions we'll ever be able to handle.

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Jul 21 '05 #8
> > Yes indeed. If I try to start a process with Process.Start() and an
exception occures who cares what kind of error it was? I display a
messagebox and inform the user what happens and display the message
from the exception.
Which depending on the exception may not work.


Sure if depends on the component. If it is one of my examples catching all
will work and doesn't cause any problems.
If it throws a fatal exception like stackoverflow, we cannot do anything
anyway since it is rethrown automatically, as are other fatal exceptions
too. Here again is the problem: There is not way telling: do not catch such
fatal exceptions. The .NET exception model is inherently broken. If there
would be at least a property in System.Exceptio n to determine wheather I can
catch that Exception or not, it would be very helpful.
Again, you're assuming that this is recoverable situation. But in truth, you don't know if an unexpected exception is recoverable. Also, I don't see the benefit of an error message saying: "Oops. Dunno what happened, but we'll
continue for now. Stay tuned." A better approach to me is
terminate-and-restart, like the way newer MS Office applications behave.
What is the problem? Fact is that database could not be opened. May it due
to a security issue, an IO-Error, a corrupted database, a denied conection,
a wrong IP or port or driver. Fact is you tell the user why the connection
could not established and tell them to try another database.
Why should we let the whole application crash? If your programs are like
that, I hope I do not need to use them..
Why do you want the whole app to shut down only because "an unknown
exception" occured during connection with the database?
You would let your application totally crash just because you third
party sound library throws a funny exception when you tried to play
background sound but the user does have funny hardware which lets the
soundcomponent totally crash. Will you really trust every third party
component? You never should.


Again, you only know that *afterwards*, when analyzing a stacktrace. At
runtime, all you can do is keep fingers crossed. A third party library
should not throw "funny" exceptions, but expose a properly designed
exception hierarchy -- otherwise it may do more harm than good.


What it should or not is clear, but nevertheless they *can* do it, and you
*cannot* do anything against it.
When your customer comes to you and tells you that your app crashed simply
because of an unknown exception
in a unimportant component of your app crash will you tell them: "oh, but it
should not throw these funny exceptions and therefore I didn't catch them."
We *can* trust our own code, sure. But we cannot trust 3rd party
components as we do not have their sourcecode.


That's probably the propert way to look at it from a security perspective,
but from an OO point of view that won't work. Either an exception is part

of a component's accessible API or not.
The problem is that in .NET unlike java an exception is not part of the
public API.
You can try to document them, but that all you can do: trying it.
If not, it is an implementation detail you should not deal with.
Sure. Let the whole app crash because I should not deal with that exception.

Let me give another example. You have an interface which represents a
database exception. Then you have a method which returns a database
connection (a class which implements that interface).
This database could base upon a network connection, a text file, an excel
file, or it may use remoting.
Sure you can document everything but if somewhere in your exception hirarchy
an exception occures which is not documented you will let you whole app die.
And can we trust our own code? No. Even our own
code can throw way more exceptions we'll ever be able to handle.


In our own code we know which exceptions we throw, we properly document them
and we have strong conventions.

--
cody

Freeware Tools, Games and Humour
http://www.deutronium.de.vu || http://www.deutronium.tk
Jul 21 '05 #9
David Levine wrote:
I disagree on the model part, but regarding the hierarchy you're
right. What's really missing is a distinction between potentially
recoverable conditions and irrecoverable failures -- lo and behold,
that's what Exception and Error in Java represent.
It isn't at all clear to me how a component that throws an exception
can determine if something is recoverable or not - perhaps there are
times it can, but there are more cases where only a higher-level
module can make that decision.


In Java, Errors are (to be) only thrown by the JVM. Don't confuse
recoverable with being able to handle. If a component throws an Exception,
it obviously cannot handle it -- but the situation can be recovered from.
And this is not the same as the SystemException vs.
ApplicationExce ption approach, which doesn't cut it anyway.


Agreed. On the surface it would be useful to have categories such as
SystemFatalExce ption, SystemCriticalE xception, but then this opens a
different can of worms - the ability to recover or not from an
exception is application dependent unless the runtime has become
corrupted and is about to shutdown.


That's why I'd like to see a different exception family that doesn't blur
the lines between a fatal system failure and some recoverable exception.

[...]
No. When you say catch (Exception) you think it means:

"This stupid API isn't properly documented, so I need to be sure."

But what it means is

"I can handle it."

Unfortunately, nothing could more mistaken. Depending on the
failure, you may hide or swallow a severe problem. Of course that's
caused by the missing distinction between Error and Exception. But
save for a global "log and die/abort" exception handler, there's
little you can do with catch (Exception).


I have come to use something like this...

catch(SomeSpeci ficException sse)
{
// recover/retry/whatever
}
catch(Exception ex)
{
throw new CloneExceptionT ype(ex,"Add some context info here."); // or
throw some other type
}

...and kick it upstairs for high-level code to deal with. Ultimately
it boils down to 2 basic choices - either the code knows how to
recover from an exception or it doesn't. If it doesn't, then you can
either allow the user to retry/cancel/abort the operation, or you can
exit the application.


Unfortunately, this could mask an OutOfMemoryExce ption or other terrible
things if the newly thrown exception type is not explicitly meant to be
fatal.
First, hopefully nobody drops an updated library in production
without prior testing. Grab the library, run your unit tests (which
hopefully cover both normal and exptected error conditions), and
check the green light. If your development process doesn't include
this very basic step, you're in trouble anyway...


I kind of disagree here; I use unit testing and it is a valuable
tool/technique but sometimes all it does is validate our own
misconceptions. It will not force a third-party component to throw
exceptions, especially ones that you did not know could be thrown -
if it did then you are really writing a unit test that validates the
component, not your own code. A unit test would probably create a
mock object for the library/component. I think testing an external
component used by your code is more of a systems test then a unit
test.


It probably depends on the level of integration that is covered by the test.
A facade that wraps technical exceptions in business interface exceptions
certainly requires such coverage at the unit level.

One problem is how a system evolves over time. Even if you nail it
and handle every specific exception in the original code base, as it
evolves and as components change there is no way to prevent them from
throwing exception types different then those thrown in the original
implementation. A robust system must have some way of dealing with
new/unexpected error conditions, and this forces it to catch and deal
with the generic Exception type.


I still don't see how ignoring or hiding potentially fatal errors
contributes to robustness. The FCL also provides several callbacks that
allow to be notified of unhandled errors.

Cheers,

--
Joerg Jooss
jo*********@gmx .net
Jul 21 '05 #10

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

Similar topics

16
5279
by: David Turner | last post by:
Hi all I noticed something interesting while testing some RAII concepts ported from C++ in Python. I haven't managed to find any information about it on the web, hence this post. The problem is that when an exception is raised, the destruction of locals appears to be deferred to program exit. Am I missing something? Is this behaviour by design? If so, is there any reason for it? The only rationale I can think of is to speed up...
21
2220
by: dkcpub | last post by:
I'm very new to Python, but I couldn't find anything in the docs or faq about this. And I fished around in the IDLE menus but didn't see anything. Is there a tool that can determine all the exceptions that can be raised in a Python function, or in any of the functions it calls, etc.? /Dan
26
2887
by: OvErboRed | last post by:
I just read a whole bunch of threads on microsoft.public.dotnet.* regarding checked exceptions (the longest-running of which seems to be <cJQQ9.4419 $j94.834878@news02.tsnz.net>. My personal belief is that checked exceptions should be required in .NET. I find that many others share the same views as I do. It is extremely frustrating to have to work around this with hacks like Abstract ADO.NET and CLRxLint (which still don't solve the...
9
2332
by: Gianni Mariani | last post by:
I'm involved in a new project and a new member on the team has voiced a strong opinion that we should utilize exceptions. The other members on the team indicate that they have either been burned with unmaintainable code (an so are now not using exceptions). My position is that "I can be convinced to use exceptions" and my experience was that it let to code that was (much) more difficult to debug. The team decided that we'd give...
6
2823
by: RepStat | last post by:
I've read that it is best not to use exceptions willy-nilly for stupid purposes as they can be a major performance hit if they are thrown. But is it a performance hit to use a try..catch..finally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..finally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
14
3467
by: dcassar | last post by:
I have had a lively discussion with some coworkers and decided to get some general feedback on an issue that I could find very little guidance on. Why is it considered bad practice to define a public member with a return type that is derived from System.Exception? I understand the importance of having clean, concise code that follows widely-accepted patterns and practices, but in this case, I find it hard to blindly follow a standard...
8
2247
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an exception should be thrown only in exceptional situations. It turned out that each of my colleagues had their own interpretation about what an "exceptional situation" may actually be. First of all, myself I’m against using exceptions extensively,...
1
2377
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
2
2960
by: Zytan | last post by:
I know that WebRequest.GetResponse can throw WebException from internet tutorials. However in the MSDN docs: http://msdn2.microsoft.com/en-us/library/system.net.webrequest.getresponse.aspx It only lists NotImplementedException in the Exceptions section. (Note that it does mention WebException in the Remarks section, but who knows if this is always the case for such classes, and thus perhaps they can't be trusted to always list these, and...
0
6493
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception. In general, you can sort Exceptions into two groups: Checked and unchecked Exceptions. Checked Exceptions are checked by the compiler at compilation time. Most...
0
8384
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8499
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,...
1
6162
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
5630
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1937
muto222
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.