473,796 Members | 2,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Exception is Unchecked???

I am using Visual Studio 2K3 writing a ASP.NET web application. Is there a
way to force the C# compiler to catch possible exception?

In Java, all exceptions thrown MUST BE caught, otherwise compiler would give
you error. In C#, is there a way to do that?

Nov 16 '05
16 6594
"Mike Schilling" <ms************ *@hotmail.com> wrote in message
news:uQ******** ******@TK2MSFTN GP14.phx.gbl...

"John Saunders" <johnwsaundersi ii at hotmail.com> wrote in message
news:eE******** ******@TK2MSFTN GP14.phx.gbl...
Java reminds you that a close does I/O that can fail (in particular
buffer flushing.) C# doesn't. Any guesses how much C# code handles
failures in Close() ?


All of mine does. ;-)


Good for you. Mine too. A lot doesn't, just in as C, a lot didn't check
the return status from close() or fclose().
Why? It isn't in .NET. Don't know about the Java case. If network
exceptions are subclasses of IOException, then tell me what is _not_ a
subclass of IOException (aside from Exception).

Illegal argument?
Invalid state?
Concurrent modification?
No such class/method/field?
Access not allowed?
etc.


> One advantage of checked exceptions is that it allows the
> documentation to know which exceptions are thrown. Compare the JDK
> Javadoc with the .NET API documentation. You'll see how much better
> the Javadoc is about showing which exceptions are thrown and why.

Should ease of automatic documentation be a reason to implement a
language feature like this? An <exception> tag in Xml comments in C#
solves this problem without constraining the language.
But the exception tags don't get put in C# methods, they do get put into
the Java ones.


The exception tags get put in by developers who want to document what
exceptions are thrown, and it didn't take a language feature to get that
done. And they're likely to be a lot more specific that "IOExceptio n".


Then why is the .NET framework documentation so poor in documenting
exceptions compared to the JDK docs?


The JDK docs naturally document what's in the throws clauses. I'm not even
sure whether the .NET documentation comes from Xml comments in C# code.

John Saunders
Nov 16 '05 #11
Really, I wasn't going to comment on this holy-war, but I think I will
anyway.

INTRO
-----

Checked exceptions seems like a good idea at first, which is probably
why it's included in JAVA. Unfortunatly it has a few problems, owing
sub-typing and the variance of errors, which makes it tempting to
declare every method "throws Throwable". I will shortly discuss the
problem with current implementations of checked exceptions and then
propose a method which makes checked exceptions beneficial in the way
checked-exception proponents usually argue it is.

EXAMPLE
-------

Let's do an example, C# syntax (this is m*.p*.d*.l*.csh arp :) with
checked exceptions as in Java.

/** Persist objects, allow retrieval by id */
interface ObjectStore {
int Store(Object);
Object Retrieve(int id);
}

Now for a specific implementation that uses a directory with files for
storage:
public class DiskObjectStore : ObjectStore {
string Directory;
Object Retrieve(int id) {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
}
}

WHAT SHOULD WE DO WITH THE D***** EXCEPTION
-------------------------------------------
(chorus: WITH THE D***** EXCEPTION)

Obviously File.Open(...) can throw a FileNotFound exception, so should
we catch and discard that? probably not, since we would deprive the
caller of accurate information about what failed.

So, we have to change the declaration of Retrieve:

Object Retrieve(int id): throws FileNotFound {...}

But that doesn't match the interface, and the interface declaration has
to be expanded to include a "throws FileNotFound". This removes the
abstractness of the interface, so you might suggest: "every
implementation of ObjectStore must do some I/O, so we'll let it throw
IOException".

Cutting heels and clipping toes
-------------------------------

This ensnaring argument hides the fundamental problem: you declared the
interface to be implementation-independant in the first place. Even
worse many implementations might NEVER throw an IOException, for example
a test-implementation:

public class MemoryStorage: ObjectStore {
IDictionary objects = new HashTable();
Object Retrieve(int id) throws IOException {
return objects[id]; // cannot throw IOException
}
}

or they might throw a whole new type of exception:

int id_count = 0;
int Store(Object o) {
int id = ++id_count; // ignore concurrency problems for now, ok?
if ( id_count == 0 )
throw new OutOfNamespace( o);
else
objects[id] = o;
}

When it's NOT a feary-tale
--------------------------

In the real world, what you end up with is usually either a global
throws declaration in the interface (and on all the callers of the
interface methods):

Object Retrieve(int id): throws Exception();

Or (nervous ticks starts) every implementation doing:

try {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
} catch ( Exception e ) {
// an error occured, lot's of info in e, let's throw it away
return null;
}

And a VERY confusing code-style (*mildly* better: Logging errors and
returning null's.)

This is what most JAVA programmers do, atleast in the code i've seen :)

Wrapping extinguish type
------------------------

The last (and worst) alternative (which unfortunatly is done in a lot of
places in .NET) is to wrap the exception:

try {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
} catch ( Exception e ) {
throw new ObjectStoreExce ption(e);
}

This prevents the caller from even catching on the actual type of
exception occuring, and thus robs him of a viable retry strategy (unless
he wants to traverse the .Inner's of exceptions looking for the real
problem. This would take HEAPS of code, especially if more than one
wrapping is done). It actually removes the whole point of having Types
exceptions :)

*** NOTE: .NET Delegate's do exception wrapping, making catch on a
delegate-invocation a VERY delicate thing to try.

So, while checked exceptions have some nice properties, they really are
tedious to work with when polymorphism is used, since they precisely
expose the implementation differences that you wished to ignore by using
polymorphism.

JAVA
----

Now, zooming in on JAVA: JAVA has excepted that having every exception
as checked is too tedious. In JAVA there are RuntimeExceptio n's that may
be thrown *without* declaration in throws statements, and we may even
declare such an exception ourselves, BUT the class heirarchy is used to
indicate whether an exception should be checked or not.

This is higly unfortunate, since it deprives the programmer of the
ability to decide seperatly from situation to situation how "important"
a specific type of exception is, whether it should be catched or not by
the caller.

PROPOSAL
--------

If it was possible to declare "throws" statements on functions and
require callers to either handle or declare the exceptions themselves
(no class-hierarchy spec. of what should be checked here), AND it was
possible to "uncheck" an exception, allowing the caller to knowingly
pass a previously checked exception from a function as unchecked, now
that WOULD be usefull.

It would allow us to write the interface from above in the way we
wanted, without any throws qualifier, but it would allow File.Open to
declare that a FileNotFoundExc eption could reasonably occur and that the
caller should do something about it.

The resulting code would be something like (with a newly invented syntax
for "unchecking ", could probably be MUCH ):

using ( Stream s =
uncheck(File.Op en(File.Combine (Directory, id.ToString())) ),
FileNotFound)
{
// fetch object
...
}

The "uncheck" generates no code, and no catch-handler, it simply
instructs the compiler that the programmer knows that the call to
File.Open may cause an exception, but that should be accepted at
runtime, rather the provably handled by the caller.

CONCLUSION
----------

In this way the intrusion of checked exceptions may be kept to a
tolerable level, and cheked exceptions declarations can be actually
utilized to indicate "hey mate, this might fail, and you better have
something up your sleeve if it does".

--
Helge
Nov 16 '05 #12
"Helge Jensen" <he**********@s log.dk> wrote in message
news:41******** ******@slog.dk. ..
Really, I wasn't going to comment on this holy-war, but I think I will
anyway.
Thanks for the comment, and thanks for bringing it out of .aspnet. I'll keep
it in the list for a while, for anyone following this there, but if this
goes on for long, I hope we can all agree that .aspnet time is over. :-)

....
*** NOTE: .NET Delegate's do exception wrapping, making catch on a
delegate-invocation a VERY delicate thing to try.
I was unaware of this. Could you provide some detail on this behavior?
PROPOSAL
--------

If it was possible to declare "throws" statements on functions and require
callers to either handle or declare the exceptions themselves (no
class-hierarchy spec. of what should be checked here), AND it was possible
to "uncheck" an exception, allowing the caller to knowingly pass a
previously checked exception from a function as unchecked, now that WOULD
be usefull.

It would allow us to write the interface from above in the way we wanted,
without any throws qualifier, but it would allow File.Open to declare that
a FileNotFoundExc eption could reasonably occur and that the caller should
do something about it.


I have some question in general about this entire area. The fact is that,
when my code can handle an exception, I handle it. But when it doesn't have
anything useful to contribute to the processing of the exception, I get out
of the way and let my callers deal with it. Maybe the caller can handle the
exception, even though there's nothing useful I can do with it right now.

I _do_ sometimes wrap exceptions with something more application-specific.
For instance, I have a Login method for logging in to a web service. This
method will wrap a SoapException in a LoginFailedExce ption. Presumably, my
caller called me in order to log in, and should be told that the login
failed. My Message says, "Can't log in as <username>", which is more useful
than "required header not supplied in call". If my caller thinks he knows
what to do about a SoapException, I supply it to him as the InnerException
property, but I don't decline to give him useful information on the off
chance that he really wanted to see that SoapException instead of my
LoginFailedExce ption.

I assume that my callers are taking care of their IDisposable resources with
"using" blocks or the equivalent. I assume they're backing out of anything
else that needs backing out of with "finally" blocks. And I assume they have
a strategy for what to do with exceptions that nobody has been able to
handle. Maybe they've got a try-catch block around their message loop, or,
perhaps they do like I often do in Windows Forms applications, and place
their entire event handler in a try-catch block. Maybe my ultimate caller is
an ASP.NET application which handles all unhandled exceptions in Global.asax
and needs to e-mail exception details to the support group and write them to
the Windows event log?

In any case, none of those questions should have anything to do with me as a
class library designer. I should handle the exceptions if I can do so
usefully, I should wrap the exceptions if I want to make them more relevant
to my direct caller, and otherwise, I should stay out of the way!

And, BTW, I should document what exceptions I throw so that my callers can
think about their exception handling strategies ahead of time. In my
documentation, I should not only indicate which exceptions I throw (which is
what a "throws" clause does in Java), but I should also indicate _why_ the
exception might be thrown and perhaps give guidance as to what a caller
might do about it:

John Saunders
Nov 16 '05 #13

"John Saunders" <johnwsaundersi ii at hotmail.com> wrote in message
news:eG******** ******@TK2MSFTN GP09.phx.gbl...
"Mike Schilling" <ms************ *@hotmail.com> wrote in message .. And they're likely to be a lot more specific that "IOExceptio n".

Then why is the .NET framework documentation so poor in documenting
exceptions compared to the JDK docs?


The JDK docs naturally document what's in the throws clauses.

Exactly my point.
I'm not even sure whether the .NET documentation comes from Xml comments in
C# code.

Nov 16 '05 #14

"Helge Jensen" <he**********@s log.dk> wrote in message
news:41******** ******@slog.dk. ..
Really, I wasn't going to comment on this holy-war, but I think I will
anyway.

INTRO
-----

Checked exceptions seems like a good idea at first, which is probably why
it's included in JAVA. Unfortunatly it has a few problems, owing
sub-typing and the variance of errors, which makes it tempting to declare
every method "throws Throwable". I will shortly discuss the problem with
current implementations of checked exceptions and then propose a method
which makes checked exceptions beneficial in the way checked-exception
proponents usually argue it is.

EXAMPLE
-------

Let's do an example, C# syntax (this is m*.p*.d*.l*.csh arp :) with checked
exceptions as in Java.

/** Persist objects, allow retrieval by id */
interface ObjectStore {
int Store(Object);
Object Retrieve(int id);
}
No exceptions defined at this level? These methods can never fail?

Let's start by thinking about how Retrieve, for example, can fail.

1. The id can fail to refer.
2. The object store in use was never initialized.
3. An error occurred fetching (e.g. deserializing) this object.

That's not exhaustive, but it's a start.

Thus:

public Object Retrieve(int id) throws NoSuchObjectExc eption,
StoreNotInitial izedException, RetrieveFailedE xception
Now for a specific implementation that uses a directory with files for
storage:
public class DiskObjectStore : ObjectStore {
string Directory;
Object Retrieve(int id) {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
}
}

WHAT SHOULD WE DO WITH THE D***** EXCEPTION


Is this supposed to be hard?

catch(IOExcepti on ex)
{
throw new NoSuchObjectExc eption("" + id + " is not a valid object
identifier", ex);
}

Nov 16 '05 #15

Thanks for all your comments. Helge comments and Richard's link are very
helpful.

C.P. [No MCSD]
"Helge Jensen" <he**********@s log.dk> wrote in message
news:41******** ******@slog.dk. ..
Really, I wasn't going to comment on this holy-war, but I think I will
anyway.

INTRO
-----

Checked exceptions seems like a good idea at first, which is probably
why it's included in JAVA. Unfortunatly it has a few problems, owing
sub-typing and the variance of errors, which makes it tempting to
declare every method "throws Throwable". I will shortly discuss the
problem with current implementations of checked exceptions and then
propose a method which makes checked exceptions beneficial in the way
checked-exception proponents usually argue it is.

EXAMPLE
-------

Let's do an example, C# syntax (this is m*.p*.d*.l*.csh arp :) with
checked exceptions as in Java.

/** Persist objects, allow retrieval by id */
interface ObjectStore {
int Store(Object);
Object Retrieve(int id);
}

Now for a specific implementation that uses a directory with files for
storage:
public class DiskObjectStore : ObjectStore {
string Directory;
Object Retrieve(int id) {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
}
}

WHAT SHOULD WE DO WITH THE D***** EXCEPTION
-------------------------------------------
(chorus: WITH THE D***** EXCEPTION)

Obviously File.Open(...) can throw a FileNotFound exception, so should
we catch and discard that? probably not, since we would deprive the
caller of accurate information about what failed.

So, we have to change the declaration of Retrieve:

Object Retrieve(int id): throws FileNotFound {...}

But that doesn't match the interface, and the interface declaration has
to be expanded to include a "throws FileNotFound". This removes the
abstractness of the interface, so you might suggest: "every
implementation of ObjectStore must do some I/O, so we'll let it throw
IOException".

Cutting heels and clipping toes
-------------------------------

This ensnaring argument hides the fundamental problem: you declared the
interface to be implementation-independant in the first place. Even
worse many implementations might NEVER throw an IOException, for example
a test-implementation:

public class MemoryStorage: ObjectStore {
IDictionary objects = new HashTable();
Object Retrieve(int id) throws IOException {
return objects[id]; // cannot throw IOException
}
}

or they might throw a whole new type of exception:

int id_count = 0;
int Store(Object o) {
int id = ++id_count; // ignore concurrency problems for now, ok?
if ( id_count == 0 )
throw new OutOfNamespace( o);
else
objects[id] = o;
}

When it's NOT a feary-tale
--------------------------

In the real world, what you end up with is usually either a global
throws declaration in the interface (and on all the callers of the
interface methods):

Object Retrieve(int id): throws Exception();

Or (nervous ticks starts) every implementation doing:

try {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
} catch ( Exception e ) {
// an error occured, lot's of info in e, let's throw it away
return null;
}

And a VERY confusing code-style (*mildly* better: Logging errors and
returning null's.)

This is what most JAVA programmers do, atleast in the code i've seen :)

Wrapping extinguish type
------------------------

The last (and worst) alternative (which unfortunatly is done in a lot of
places in .NET) is to wrap the exception:

try {
using ( Stream s =
File.Open(File. Combine(Directo ry, id.ToString())) ) {
// fetch object
...
}
} catch ( Exception e ) {
throw new ObjectStoreExce ption(e);
}

This prevents the caller from even catching on the actual type of
exception occuring, and thus robs him of a viable retry strategy (unless
he wants to traverse the .Inner's of exceptions looking for the real
problem. This would take HEAPS of code, especially if more than one
wrapping is done). It actually removes the whole point of having Types
exceptions :)

*** NOTE: .NET Delegate's do exception wrapping, making catch on a
delegate-invocation a VERY delicate thing to try.

So, while checked exceptions have some nice properties, they really are
tedious to work with when polymorphism is used, since they precisely
expose the implementation differences that you wished to ignore by using
polymorphism.

JAVA
----

Now, zooming in on JAVA: JAVA has excepted that having every exception
as checked is too tedious. In JAVA there are RuntimeExceptio n's that may
be thrown *without* declaration in throws statements, and we may even
declare such an exception ourselves, BUT the class heirarchy is used to
indicate whether an exception should be checked or not.

This is higly unfortunate, since it deprives the programmer of the
ability to decide seperatly from situation to situation how "important"
a specific type of exception is, whether it should be catched or not by
the caller.

PROPOSAL
--------

If it was possible to declare "throws" statements on functions and
require callers to either handle or declare the exceptions themselves
(no class-hierarchy spec. of what should be checked here), AND it was
possible to "uncheck" an exception, allowing the caller to knowingly
pass a previously checked exception from a function as unchecked, now
that WOULD be usefull.

It would allow us to write the interface from above in the way we
wanted, without any throws qualifier, but it would allow File.Open to
declare that a FileNotFoundExc eption could reasonably occur and that the
caller should do something about it.

The resulting code would be something like (with a newly invented syntax
for "unchecking ", could probably be MUCH ):

using ( Stream s =
uncheck(File.Op en(File.Combine (Directory, id.ToString())) ),
FileNotFound)
{
// fetch object
...
}

The "uncheck" generates no code, and no catch-handler, it simply
instructs the compiler that the programmer knows that the call to
File.Open may cause an exception, but that should be accepted at
runtime, rather the provably handled by the caller.

CONCLUSION
----------

In this way the intrusion of checked exceptions may be kept to a
tolerable level, and cheked exceptions declarations can be actually
utilized to indicate "hey mate, this might fail, and you better have
something up your sleeve if it does".

--
Helge

Nov 16 '05 #16
"Mike Schilling" <ms************ *@hotmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

"John Saunders" <johnwsaundersi ii at hotmail.com> wrote in message
news:eG******** ******@TK2MSFTN GP09.phx.gbl...
"Mike Schilling" <ms************ *@hotmail.com> wrote in message

. And they're likely to be a lot more specific that "IOExceptio n".

Then why is the .NET framework documentation so poor in documenting
exceptions compared to the JDK docs?


The JDK docs naturally document what's in the throws clauses.

Exactly my point.


And my point is that one should hire tech writers to write documentation,
not compiler designers.

John Saunders
Nov 16 '05 #17

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

Similar topics

0
13668
by: Steven Buroff | last post by:
I can't seem to get the @SuppressWarnings("unchecked") to work. Here is my test program. public class Tryit { @SuppressWarnings({"unchecked"}) public <T> T doit(Class<T> clazz){ T val = (T)"xxx"; return val; } }
17
3148
by: Bryan Bullard | last post by:
hi, is there a way to force the user of an object to catch exceptions of specific type? for instance a compile error is issued if exception 'ExeceptionXXX' thrown by method 'ThrowsExceptionXXX' is not caught. thanks,
16
1302
by: ChInKPoInt [No MCSD] | last post by:
I am using Visual Studio 2K3 writing a ASP.NET web application. Is there a way to force the C# compiler to catch possible exception? In Java, all exceptions thrown MUST BE caught, otherwise compiler would give you error. In C#, is there a way to do that?
41
3083
by: Stuart Golodetz | last post by:
Hi all, Just wondering whether there's any reason why exception specifications are enforced at runtime, rather than at compile-time like in Java? (This was prompted by reading an article on GOTW, incidentally.) Is there something about C++ that makes it harder/impossible to check at compile-time? Cheers, Stu
2
2485
by: Spawn666948 | last post by:
Hey, do you guys know how to set the Name Autocorrect to unchecked by default. Name Autocorrect is more trouble than its worth. I know I can go to Tools/General, but, I'd rather have it unchecked by default when I create a blank database. Thanks.
6
1624
by: Bruce | last post by:
I have a reference assembly that I wrote. The assembly can throw exceptions. I am handling these exceptions but, when running my code from VB, VB still insists on setting a breakpoint where the exception is being thrown inside the assembly. Is there anyway to avoid this? If so how?
8
4349
by: pjerald | last post by:
package test; import java.util.ArrayList; public class MyArrayList{ public static void main(String args) { ArrayList al = new ArrayList(); al.add("Jerald"); al.add("PJerald");
1
2471
by: ttamilvanan81 | last post by:
Hai i have using the checkbox in for loop. I need the urgent help from anyone, for example in the loop there is having 5 checkbox if i checked 3 of the ckeckboxes and 2 of the checkboxes are unchecked. I need to get the values for checked checkboxes and unchecked checkboxes. Because if i checked the checkboxes, those values need to be inserted into the database. Those for unchecked checkboxes values need to be deleted from the database. Can...
1
3299
oll3i
by: oll3i | last post by:
E:\ECLIPS~1\ZADANIE3\SRC\EJB>javac -Xlint:unchecked ManageDBBean.java ManageDBBean.java:34: warning: unchecked conversion found : java.util.HashMap required: java.util.Map<java.lang.String,java.lang.String> rowsMap = new HashMap; ^ 1 warning Map<String, String> rowsMap = null;
0
9528
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,...
0
10228
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
10173
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
9052
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...
0
6788
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
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4116
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
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
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.