|
Mark Nischalke wrote: catch(UserIsMoronException ex)
They REALLY need to add this one to the framework.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
John Simmons / outlaw programmer wrote: Mark Nischalke wrote:
catch(UserIsMoronException ex)
They REALLY need to add this one to the framework.
They did, and 85% of the exceptions where caught by, ... you guessed it right...
|
|
|
|
|
Having a type-safe object has some advantages over a string.
It's harder to filter if you're examining a string, and I like having a class that describes the problem and being able to catch and handle that specific case. Or worse- let the user decide whether or not those kind of exceptions need be logged (like file-access errors for the sysadmin, common networkexceptions for the networkadmin, and whether the user allows the app to send unhandled exceptions with a stacktrace back home) There's a string in the custom exception of course, along with placeholders for values to help diagnose the problem. But in code, I can act on the object itself, and I don't need to depend on the formatting of a string.
It's a matter of preference, I guess, as you can accomplish the same visual and functional endresult.
No, the worst kind of exceptions are translated ones. Yes, I know about the unlocalize website, but that's not exactly convenient. I'm hoping that I can rectify some by removing the .NET language packs from my PC.
I are Troll
|
|
|
|
|
John Simmons / outlaw programmer wrote: I generally just do this instead of creating custom exception objects:
catch (Exception ex)
{
throw new Exception("My custom exception message", ex);
}
I believe that is a mistake. I discuss this on my article[^], more deeply but there are 3 main problems with this approach:
1. Internationalization: when you need to catch your exception you'll need to have some sort of switch on the text message. With i18n, which message should you use on the switch?
2. You'll force your users to catch (Exception ex), which is a too broad class and they'll need to handle a lot of other different exceptions.
3. You'l force your users to stop using the more efficient catch (XXXXException) and use a switch instead, which is both less readable and less efficient.
|
|
|
|
|
The well designed application doesn’t needs exceptions!
In a more serious note, the only case I create custom exceptions is when I’m dealing with COM objects and/or native libraries in order to wrap their error handling and error messages. In any other cases the build-in exceptions and re-throwing them in some cases seems to be enough for me.
There is only one Ashley Judd and Salma Hayek is her prophet!
Advertise here – minimum three posts per day are guaranteed.
|
|
|
|
|
Depends on the situation. Mostly one should use built in exceptions, but for some reason the exception is too generic or does not fit in your scenario, then creating a custom exception is better.
|
|
|
|
|
My decision is to define a custom exception when the need to do so is... well... exceptional
Really though…
If you have an exception definition that clearly fits an existing model then use it, why reinvent the wheel at all?
If you are creating a new failure state, usually most likely based upon things like a domain specific business rule, then you define a new exception of your own design. BUT you have to keep in mind that quite often even doing this can cause issues because as we all know business rules change. This means that you may want to be slightly less specific and more generalized by defining a business rule exception and allowing it to express the rule broken, and the why it was considered broken enough to trigger the exception.
I would like to know what books you say are specifically stating that new exceptions should always be defined instead of using the Dotnet ones. I would have to have a conversation with that author I am not even sure I see the value in writing all custom exceptions when creating a whole new code library of your new library is something that sits on top of the Dotnet framework. If you are writing something that is completely disconnected at all form the Dotnet stuff then yeah, you have to create your own exceptions to throw, but that makes no sense in this context really since your question was more related to being told to not use Dotnet exceptions .
If you did want to keep all the exceptions specific to your application layer then there is nothing from stopping you from writing all your own custom exception code, but I would still recommend that you consider catching the Dotnet specific stuff and then just re throwing your own as a general application side exception and then include the Dotnet exception in that object. Seems a bit messy but I guess it is doable and will not require too much writing on your part. Just remember that every additional line of code you have to write can possibly introduce a new error (and thus CAUSE an exception ) so I like to keep them down to a minimum.
One other argument I would make for maintaining the existing exceptions provided by the framework is that anytime they change you need to ensure that your code changes also. This means that if you have wrapped all of the Dotnet exceptions in your code, any time the framework changes you have to review all those changes to see what effects they have on your code. Not that you may not have to do the same if the base libraries change their exceptions and you have to catch them, but usually one of a few things happen there. First, they will keep the older exception around for a while tagged in the new framework that it is being pulled soon so that new code compilation will not allow the use of it but existing code can still use it, and second you have some time to make changes. This is also a good reason to always be sure to include a general catch statement if you want to be sure that you can grab any problems that come up due to your missing a specific exception that perhaps is not well documented or you just missed.
Whew.. a long response…
|
|
|
|
|
I think you would do this when you want to specify additional information beyond a string message describing what went wrong. Some exceptions take advantage of their name to provide additional information, like NullReferenceException. If one is thrown, clearly something is null and the code didn't expect it to be. SqlException contains additional properties related to line numbers in stored procedures that failed, for example.
So, if you'd like to provide additional properties to describe what went wrong, create a class that inherits Exception that has those properties.
|
|
|
|
|
I'll typically only write custom exceptions in the Model (Business) layer. The reason for doing this is so the presentation layer can consume the exception and display a message which is non-technical and meaningful to the user. Probably breaches best practices but it works well example:
Model receives an OutOfRangeException, Model creates a MyModelException with the message "The number of passengers must be greater than 0" and throws the exception to the presentation layer.
Architecture is extensible, code is minimal.
|
|
|
|
|
Wow! What a response. Thanks to everyone. Some very good advice in there, and lots to think about. I'm glad I asked; that was really helpful.
Best wishes, Patrick
|
|
|
|
|
Patrick. There are some questions which it is a joy to answer, and this is definitely one of them. Good question.
|
|
|
|
|
Patrick Skelton wrote: According to some books I have read, the exceptions built into .NET should generally be reserved for .NET's own use
If that was the case, why the hell are those classes public? I have never read anything like that.
You should be creating custom exceptions only when your code interacts with something external. For instance, a service should return custom exceptions back to client in order to hide the complete information of the actual exception. Not because you are ashamed of it but it doesn't makes sense client knowing details of services. Same logic I use in case anything wrong happens in database. Apart from my data layer code, none of the layers get the complete trace of the error.
Apart from all the custom exceptions, I also keep one catch block taking in Exception as a type (in the outermost code layer) just in case we get an exception which I have not handled properly.
|
|
|
|
|
In my opinion there are two situations which REQUIRE the creation of your own exception class.
1. You have a business or data layer checking errors from data entry and throwing an exception. Example: Customer name is missing. By having an exception class specific to your application, the user interface can then create custom error messages attach them to the appropriate user control and display them in a user friendly way that is specific to your application. This also allows for easy implementation of internationalization (localization) by allowing you to create a module that will pick the language specific error message for each individual situation. You don't really want to do that kind of localization at the lower levels.
2. You are implementing a service that crosses machine boundaries. In that case, you want an exception class that serializes well and provides the necessary detail to both debug any situation and to provide sufficiently detailed error messages that will be useful to the end user.
Personally, I am still trying to get used to the idea that throwing exceptions is an appropriate coding practice at an application level. I come from an assembly language and UNIX background where "exceptions" were machine-level faults that totally destroy the application code context, so it was something you would never do in application code. But in the .Net world, throwing exceptions is just as appropriate for handling application errors as returning an error code would be in the UNIX world.
Robert Tanenbaum
|
|
|
|
|
Hi, Robert,
Thanks for that.
I know what you mean about exceptions. I too cut my teeth on assembly language, and even when I started venturing into C/C++ (in video games), exceptions were to be avoided wherever possible. In fact, one game I worked on shipped with a release exception handler that simply did while( 1 );.
Best wishes, Patrick
|
|
|
|
|
Note : This one is Extreme Hypothetical dream
Is it possible to build a CPU that understands Itermediate Language straight away. ( No JIT, No unmanaged)
What could be the blocking factor's if we can't take it to the next Consumer Electronic Show (CES)
Regards,
Vythees
Miles to go before sleep...
|
|
|
|
|
Theoretically, it would be possible. However, if you removed JIT from the equation, for instance, how would you expect the application to be optimised? If you remove unmanaged, then how do you expect to accomplish tasks such as file writing?
|
|
|
|
|
I think(dream) current branch prediction technique in CPU can be scaled to optimize the code.
I think we won't design a unmanaged process. We can design a process which understands AppDomains. Which will track all the resource instance. ( Hope GC will be embedded in the BIOS itself too).
Not sure If I am making clear.
Regards,
Vythees
Miles to go before sleep...
|
|
|
|
|
It's an interesting idea, but how do you go about ensuring that you can enhance the underlying platform? How do you separate out the runtime from the processor itself?
|
|
|
|
|
Hmm.., I need to backtrack from the idea of placing GC in Bios. Better It should be a managed OS which should be built purely by IL.
Its could be like scaling a CLR itself to a complete OS.
Hope when we build we don't have bussiness compulsion to support backward compatibility (16bit DOS PAC-Man game's)
Regards,
Vythees
Miles to go before sleep...
|
|
|
|
|
Have you checked out Singularity at MS Research. It doesn't run MSIL natively, but is a completely CLR(ish) O/S, with many improvements. Very Radical.
Singularity[^]
|
|
|
|
|
Or even better is the COSMOS project. They include a compiler to turn IL into ASM, but everything else is written in C#
|
|
|
|
|
Goooood questions.
Modern processors decode opcodes into microcode when loading code into the CPU cache (at least, last time I checked. Those buggers change so fast!)
That would be a decent place for optimizaitons, though I agree it's not fun to throw that away.
But then, there are two things:
- the code in the cache can be optimized to current calling conditions
- optimizations independent of calling conditions can be written back to the in-memory code
For the second, you need some "SystemLevel" code that allows unsafe operations, e.g. ILProcessor.Primitives.Out(portNumber, Value) . It needs to be different from .NET's "unsafe" in that you can declare infection stoppage - i.e. "this class is a safe wrapper around its unsafe operations".
Implementing the optimizations in hardware would probably be painfully stupid. However, the write-back-optimizations need to be done only once, and can be done in "native" code. State dependent on-the-fly optimizations could be done in a small "helper CPU" running some hardwired FORTRAN code.
|
|
|
|
|
I haven't heard of any serious attempt to create a CIL processor yet, and I don't expect any now. It would be very similar to a Java Bytecode Processor, see here[^]; I remember aJile was one of the first of those. Nothing much came from any of those AFAICR, as they did not find a sweat spot in the market while RISC processors and RISC technologies in general were making huge inroads in the processor market.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Thanks for the answer.
I think a sweet spot may be certain middleware and asp.net appserver where pure performance in demand.
Hope one day I could see one. ( Again. Sure I will not use )
Regards,
Vythees
Miles to go before sleep...
|
|
|
|
|
You're welcome.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|