I have a lot of classes that have been written in C#.NET, and I need to know what exceptions can be thrown by them. How I can do it in Visual Studio 2005.
You pretty much can't. Firstly, .NET/C# don't have checked-exceptions like Java, and secondly there are a number of general exceptions that could happen for any freaky reason.
On a method-by-method basis, you can decorate methods with the exceptions they raise, but this is not guaranteed to be present, accurate or complete.
In general, though, any unexpected* exception should be treated as terminal; just unwind, cleaning up (using) etc as you go and propagate the exception - or at least log it if the operation isn't critical.
*=I'll leave aside the philosophical discussion of whether an exception should every truly be expected as such...
You have to look at the code, it is the only source for this.
It is possible to specify what exceptions can be thrown in xml comments but it is not mandatory, so often this imformation is missing.
I just found in a project:
try
{
myLabel.Text = school.SchoolName;
}
catch
{
myPanel.Visible = false;
}
I want to talk to the developer than wrote this, saying that incurring the null exception (because school might theoretically be null, not myLabel) would virtually make the computer beep three times and sleep for two seconds. However, I wonder if I'm misremembering the rule about that. Obviously, this isn't the intended use for try/catch, but is this bad because it defies intention, or bad because of performance considerations? I feel like it's just bad, but I want to say more than "that's really bad".
You should not use exceptions for control flow simply because it is bad design. It doesn't make sense. Exceptions are for exceptional cases, not for normal flow. Performance probably won't be an issue in this situation because for most modern applications on modern hardware, you could throw exceptions all day long and the user wouldn't notice a performance hit. However, if this is a high performance application processing a lot of data or doing a lot of some sort of work, then yes, performance would be a concern.
In my opinion this is poor because it could be made much more clear with an if statement:
if (school != null) {
myLabel.Text = school.SchoolName;
}
else {
myPanel.Visible = false;
}
That will certainly avoid using exception handling unnecessarily and make the code's meaning very obvious.
I think this is bad because it is coding against an exception for one and it will also inherit unnecessary overhead. Exceptions should only be caught if they are going to be handled in a specific way.
Exceptions should be caught specifically for Exceptional cases that you can not predict, in this case it is a simple check to see if school can be null, in fact it is expected that school might be null (since the label is set nothing). If school was null and it should not have been than it should throw its own ArgumentNullException.
Exceptions do incur runtime overhead, but it's probably negligible here. There will be a difference running in the debugger, but the built binaries should run at pretty much the same speed.
Tell your developer that any chimp can make code the machine can read. Good code is written for human beings, not machines. If a null exception is the only thing you're worried about, then it's probably a bug in the user's code -- noone should ever try to assign null to anything that way. Use an Assert() statement instead.
You are absolutely right that this is bad. It is bad because it defies intention and because it hurts performance.
I realize there is room for different programming styles, but personally, I think that even though this works, and I can see what the code is attempting to do, it also hurts readability and code clarity, making it that much more difficult for the maintenance programmers to follow. An if statement is much more appropriate here.
Throwing exceptions does have a negative impact on performance, see http://msdn.microsoft.com/en-us/library/ms229009(VS.80).aspx
I never like using exceptions for flow control. Exceptions are expensive, and it is difficult to determine what the actual flow of a program with exceptions being thrown to reach other places in code. To me this is like using GoTo. This doesn't mean that you should avoid exceptions, but rather an exception should be just that, an exception to what should normally happen in the program.
I think a worse part of the code, is that it's not even doing anything with the exception. There is no logging or even an explanation as to why the exception is being thrown.
I agree with everyone here--it's a horrible idea.
There are a few cases in Java (I think they are mostly gone now, but there may still be some in external libraries) where you were required to catch an exception for certain "non-exception" cases.
In general, when writing library code (well, any class actually), avoid using exceptions for ANYTHING that could possibly be avoided. If it's possible that a name field isn't set and that should cause an exception in a write() method, be sure to add an isValid() method so that you don't actually HAVE to catch the exception around the write to know there is a problem.
(Bad Java code addendum): this "good" programming style virtually eliminates any need for checked exceptions in Java, and checked exceptions in Java are the Suck.
I know that this probably doesn't really matter, but I would like to know what is correct.
If a piece of code contains some version of throw new SomeKindOfException(). Do we say that this piece of code can potentially raise an exception? Or throw an exception?
The keyword is throw, so I am kind of leaning towards that, but to raise an exception is also used a lot...
Do they have some sort of different meaning? Does one of them sort of implicate a difference over the other? Or is it just two words meaning exactly the same thing?
In C# terminology, raising is used in the context of events and throwing is used in the context of exceptions.
Personally, I think throw/catch combination is more beautiful than raise/catch.
I can't speak for C#, but in C++ "throw" was chosen because "raise" was already taken as a standard function name.
I think while throw is the better one, the two terms are interchangeable. Very useful if you have to use it twice in some text so that you avoid repeating the same word. But that's stylistics which is not necessary for technical writing (but still a nice thing to have).
The terminology of the various languages favors 'throw'. And I agree that 'throw' makes a lot more sense considering this is the keyword used and the compiler/language documentation always refers to exception being 'thrown'.
However, in the belly of the behemoth exceptions are actually Raised, not thrown. If you find yourself deep enough in debugger staring at an EXCEPTION_RECORD then you talk in the terminology of SEH, in which the particular class of compiler/language exceptions (eh, clr, vcpp) is just one of the many flavors exceptions come as. I guess the original conditions for which exceptions where raised for, like page faults and stack overflows, were conditions 'noticed' by the kernel that was 'informing' the user mode of the condition and not exception the user code was 'throwing' onto himself, so the term makes more sense in that context.
Either throw or raise seems fine, they mean the same to me. I wouldn't write it, but when I'm talking, I usually say 'chuck an exception'.
For events I'd use either 'fire an event' or 'raise an event'.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Do you prefer checked exception handling like in Java or unchecked exception handling like in C# and why?
I think checked exceptions are a failed experiment. The original goal of exception was to eliminate the need to validate every function call return, which was resulting in programs programs that are difficult to read, and probably inefficient as well, thus discouraging programmers from signaling and handling exceptions.
While great on paper, in practice the checked exceptions reintroduced the very same problem exception were supposed to eliminate in the first place. They add a tightly coupling between the layers of application. They make it impossible for libraries to change their implementation in subsequent versions. The link posted by crausher goes into details and explain the problems much better than I ever could.
Meh.
Checked exceptions are a great thing when used properly, but more often than not they lead to stuff like:
doSomething();
try
{
somethingThrowsCheckedException();
}
catch(ThatCheckedException)
{ }
doSomethingElse();
And, frankly, that's just wrong. You should let exceptions you don't handle bubble up.
Checked exceptions used properly can be good. But very frequently, the result of doing checked exceptions properly is method signatures like this:
public void itMightThrow() throws Exception1, Exception2, Exception3, Exception4, // ...
Exception12, Exception13, /* ... */ Exception4499379874
{
// body
}
Am I exaggerating? Only slightly.
Edit:
That said, one thing I prefer about C# over Java when it comes to exception handling has nothing to do with checked exceptions (I can get that if I go with Spec# anyway). No, what I like is that the stack trace in C# is populated when you throw an exception, rather than when you instantiate one as it is in Java.
Edit 2: This is for the commenters #Yishai, #Eddie, #Bill K:
First, you should check out this thread for information on how to get a stack trace without instantiating an exception. Keep in mind that walking the stack is a heavy process and should not be done on a regular basis.
Second, the reason I like C#'s exception stack trace being populated at throwal rather than at instantiation is that you can do things like this:
private MyException NewException(string message)
{
MyException e = new MyException(message);
Logger.LogException(message, e);
return e;
}
// and elsewhere...
if(mustThrow)
{
throw NewException("WHOOOOPSIEE!");
}
That's a trick you can't do in Java without having the NewException method included in the stack trace.
I prefer checked exceptions for things that can go wrong that you cannot predict ahead of time. For example, IOException, or SQLException. It tells the programmer that they have to account for something unpredictable going wrong, they cannot write robust code that will not throw an exception, no matter how much they try.
Too many times programmers view a checked exception as a language thing to handle. It isn't (or won't be in a well designed API) - it is an indication that there is unpredictable behavior inherent in the operation, and you should rely on a deterministic result of the operation always working the same given the same inputs.
That being said, in practice checked exceptions suffered from two things:
Not all applications written in Java need that robustness. A compiler-level flag to turn off checked exceptions would be nice - although that could lead to APIs abusing checked exceptions when their developers work with the flag set to turn them off. After thinking about a better comprimise here, my current thinking is that a compiler warning is the best ballance here. If checked exceptions were compiler warnings, including a compiler warning if one was ignored several layers down (so the fact that one was ignored would be compiled into the class), so that the caller would at least know to catch Exception even if he couldn't know which one, then those who don't care would ignore the compiler warning, and those who do would not, without anyone being forced to write error handling code they don't care about to get their code to compile.
Exception chaining took much too long (version 1.4) to introduce. The lack of exception chaining caused a lot of bad habits to develop early, instead of everyone just doing:
throw new RuntimeException(e);
when they didn't know what to do.
Also, a checked exception is another API design element to potentially get wrong, and the users of the API have to suffer with the design flaw.
EDIT: Another answer points to two issues that motivated the C# design decision of no checked exceptions. To my mind, both of those arguments are very bad, so I thought they were worth addressing/counter balancing.
Versioning. The argument is that if you change your API implementation and want to add additional checked exceptions, then you break existing client code.
Scallability. Before you know it you have a method that throws 15 checked exceptions.
I think both versions suffer from the unaddressed point that when those remarks were made it was already accepted that the proper way to deal with a checked exception moving up to the next level would be by wrapping a different checked exception appropriate to the abstraction of your API. For example, if you have a storage API that could deal with IOException, SQLException, or XML related exceptions, a properly desgined API would hide those differences behind a general PersistanceException or something like that.
Besides that general design guidance, in the specific the arguments really lead to a lot of questions about the alternatives:
Versioning. So a developer developed against your database API, thinking that they caught and handled the relevant exceptions (say DatabaseException) and then you decide in the next version to add a NetworkException to capture network level communication issues with the database. Now you just broke all compatability with existing code, and the compiler won't even complain about it. Everyone gets to discover it in regression testing, if they are lucky.
Scalability. In the C# solution, if three API levels down there is a potential for access to a volatile resource, you are relying entirely on the API documentation, because the compiler won't tell you that.
That is a great design for web apps where dying and showing the user a nice error 500 page is about all anyone bothers doing (since transactions are handled by the container anyway). But not all applications are built with such requirements in mind.
The argument ends up boiling down (to me anyway): Don't worry about exceptions, anything can go wrong and just build a catch-all.
OK. That is the core difference between a checked and unchecked exception approach. The checked exception alerts the programmer to volatile unpredictable calls. The unchecked exception approach just assumes that all error conditions are of the same class, they just have different names, and they are made unchecked so that no one goes around catching them.
Now the arguments do have merit at the CLR level. I agree that all checked exceptions should be at the compiler level, not the runtime level.
I have never used Java, but since I read
Why doesn't C# have exception specifications?
Does Java need Checked Exceptions?
The Trouble with Checked Exceptions
I am quite sure I don't like checked exceptions (in the current implementation).
The two main points mentioned are the following.
Versionability
Anders Hejlsberg: Let's start with versioning, because the issues are pretty easy to see there. Let's say I create a method foo that declares it throws exceptions A, B, and C. In version two of foo, I want to add a bunch of features, and now foo might throw exception D. It is a breaking change for me to add D to the throws clause of that method, because existing caller of that method will almost certainly not handle that exception.
Adding a new exception to a throws clause in a new version breaks client code. It's like adding a method to an interface. After you publish an interface, it is for all practical purposes immutable, because any implementation of it might have the methods that you want to add in the next version. So you've got to create a new interface instead. Similarly with exceptions, you would either have to create a whole new method called foo2 that throws more exceptions, or you would have to catch exception D in the new foo, and transform the D into an A, B, or C.
Scalability
Anders Hejlsberg: The scalability issue is somewhat related to the versionability issue. In the small, checked exceptions are very enticing. With a little example, you can show that you've actually checked that you caught the FileNotFoundException, and isn't that great? Well, that's fine when you're just calling one API. The trouble begins when you start building big systems where you're talking to four or five different subsystems. Each subsystem throws four to ten exceptions. Now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. You end up having to declare 40 exceptions that you might throw. And once you aggregate that with another subsystem you've got 80 exceptions in your throws clause. It just balloons out of control.
In the large, checked exceptions become such an irritation that people completely circumvent the feature. They either say, "throws Exception," everywhere; or—and I can't tell you how many times I've seen this—they say, "try, da da da da da, catch curly curly." They think, "Oh I'll come back and deal with these empty catch clauses later," and then of course they never do. In those situations, checked exceptions have actually degraded the quality of the system in the large.
OK, I wasn't going to reply, but this is taking too long to get closed and got many answers on one side of the fence, so I feel the need to weigh in on the other side.
I support checked exceptions -- when properly used -- and believe that they are a Good Thing. I've heard all of the arguments above many times, and there is some merit in some of the arguments against checked exceptions. But on net, I think they are positive. Having programmed in C# and Java, both, I find C# programs are more difficult to make stable against Exceptions. The great thing about checked exceptions is that the JavaDoc is guaranteed to tell you that the Exceptions can be thrown from that method. With C#, you rely on the coder to remember to tell you what exceptions may be thrown from any given method, and also what exceptions may be thrown from any method called by that method, and so on.
If you want to create 5-9's reliable code, you need to know what exceptions can be thrown from code that you call, so you can reason about what can be recovered from and what must cause you to abandon what you are doing. If C#, you can do this, but it involves a lot of trial and error until you have seen all of the possible exceptions that can be thrown. Or you just catch Exception and do your best.
There are pros and cons to both approaches, that of Java and C#. Reasoned arguments can be made in favor of both, and against both. Again, on net, I prefer the approach chosen by Java, but were I to re-write Java today, I would change the APIs to change some checked exceptions into runtime exceptions. The Java API is not consistent in its use of checked exceptions. And as someone else said, it took far too long for Exception chaining to appear as a standard API feature and a part of the JVM.
However, the charges that are lain at the feet of checked exceptions too often fall into the category of, "lazy programmers misuse this language feature." That's true. But that's true of many languages and their features. The "lazy programmer" argument is a weak one.
Let's address the main complaints that don't fall into the "lazy programmer" bucket:
Versionability - yes, throwing a new Exception in a new version of your code will break compilation for clients who blindly drop in your new JAR file. IMO, this is a good thing (as long as you have a good reason for throwing an additional checked exception), because the clients of your library have to reason about what they need to do with this behavior change. If everything is unchecked, then your clients don't necessarily have any clue (until an Exception occurs) that your behavior has changed. If you are changing the behavior of your code, then it's reasonable for your clients to have to know about this. Have you ever updated to a new version of a 3rd party library only to find its behavior has invisibly changed and now your program is broken? If you make a breaking behavior change in your library, you should break automatic compatibility with clients using earlier versions of your library.
Scalability - If you handle checked exceptions properly by translating them to a specific checked (or unchecked) exception appropriate to your layer of the API, this becomes a non-issue. That is, if you code properly, this problem disappears. And doing so, you properly hide your implementation details, which your callers shouldn't care about anyway.
Too often, this is simply a religious issue with people, and that's why I get (unnecessarily, I know) irritated. If you have a religious aversion to checked exceptions, that's OK. If you have a reasoned argument against checked exceptions, that's OK. I've seen good reasoned arguments (that I mostly don't agree with, but still...). But mostly I see bad arguments against checked exceptions, including arguments which were fair and reasonable when talking about Java 1.0, but which are no longer applicable given modern releases of Java.
In practice it is better to use checked exception handling as it allows for more detailed information when your app begins flooding error logs at 2AM and you get a call to do some debugging...
In my opinion there exist cases where checked exceptions are appropriate. There are probably features that could be done differently in Java to better support them. It isn't without difficulties (for instance, in some situations you might want an exception checked, in others not). Java does, of course, support unchecked exception types as well.
The sort of exceptions that are suitable to be checked should generally be documented. The best place to document is in the code. The populist approach is just to botch it and only consider the happy case.
Checked exceptions are great as long as they are recoverable or not due to programming errors like an invalid index acces to a ResultSet. Otherwise they tend to pollute code layers and APIs by forcing the coder to declare things like IOException in many method signatures and giving nothing really useful to the client code.
I think in most cases checked exception are a waste of time. They entrap to things like the antipattern mentioned by randolpho or extensive creation of custom exceptions to decouple your implementation from used libraries.
Beeing rid of this 'feature' lets you focus on what you want to do.
The only thing I'dd like the compiler to check for me is whether a function throws exceptions or not. What specific exceptions that can be thrown doesn't matter. The thing is that in my experience, there are a lot functions that don't throw anything, and it would be nice if this was documented in the function specification. For these functions you don't have to worry about exception handling.
Java has compiler checked exceptions. When I made transition to C++, I learned it doesn't feature checked exceptions. At first, I kept using exception handling, because it's a great feature. However, after a while I abandoned it, because I got into a situation every function might throw an exception. As only a small percentage of the functions I write can throw exceptions (say some 25% at the most), I found the overhead of doing exception handling for functions that cannot throw anything unacceptable.
Because of this, I am really surprised that there are a lot of developers who prefer unchecked exceptions. Therefore, I am curious to know how they handle this problem. How do you avoid the overhead of doing unnecessary exception handling in case the language doesn't support checked exceptions?
Remark: My question equally applies to C++ and C#, and probably to all other languages that don't feature compiler checked exception handling.
Simple. You don't do exception handling in "every function that might throw" - in C++, just about every function might do so. Instead, you do it at certain key points in your application, where you can produce a sensible, application-specific diagnostic and take sensible, application-specific corrective action, although use of the RAII idiom means (as avakar points out in his answer) that there is often little corrective action to be taken.
When I first started using C# I was scared by this too. Then I found that actually, it doesn't matter very often. I very rarely find that I can catch an exception and so something useful with it anyway... almost all my exceptions bubble up to somewhere near the top of the stack anyway, where they're handled by aborting the request or whatever.
Now when I'm writing Java, I find checked exceptions intensely frustrating a lot of the time. I think there's value in there somewhere, but it introduces as many problems as it solves.
Basically, I think we haven't really got the whole error handling side of things "right" yet, but on balance I prefer the C# approach to the Java approach.
In addition to what Neil said, you should note that there is no need for try/finally (or in context of C++ try/catch/throw), because object destructors are called even if an exception is thrown.
It is easily possible to have exception-safe code with very few try statements.
For C++ specifically, the overhead pretty much goes away if you design your classes well and use RAII.
Martin York has written a wonderful example of that in this answer.
The function can stll throw an exception, yes, but if it does, it won't need to do anything special to clean up. So you only need to actually catch the exception in one place -- the function that is able to handle it and recover from the error.