Why do most exceptions omit instance-specific information? - c#

I've noticed that most exception messages don't include instance-specific details like the value that caused the exception. They generally only tell you the "category" of the error.
For example, when attempting to serialize an object with a 3rd. party library, I got a MissingMethodException with message:
"No parameterless constructor defined for this object."
In many cases this is enough, but often (typically during development) a message like
"No parameterless constructor defined for this object of type 'Foo'."
can save a lot of time by directing you straight to the cause of the error.
InvalidArgumentException is another example: it usually tells you the name of the argument but not its value.
This seems to be the case for most framework-raised exceptions, but also for 3rd party libraries.
Is this done on purpose?
Is there a security implication in exposing an internal state like the "faulty" value of a variable?

Two reasons I can think of:
Firstly, maybe the parameter that threw the exception was a value that was a processed form of the one that was passed to the public interface. The value may not make sense without the expense of catching to rethrow a different exception that is going to be the same in most regards anyway.
Secondly, and more importantly, is that there can indeed be a security risk, that can be very hard to second-guess (if I'm writing a general-purpose container, I don't know what contexts it will be used in). We don't want "Credit-Card: 5555444455554444" appearing in an error message if we can help it.
Ultimately, just what debug information is most useful will vary according to the error anyway. If the type, method and (when possible) file and line number isn't enough, it's time to write some debug code that traps just what you do want to know, rather than complaining that it isn't already trapped when next time you might want yet different information (field state of instances can be just as likely to be useful as parameters).

InvalidArgumentException and (per #Ian Nelson) "Key not found in dictionary" both share something in common - there's no guarantee that the framework would be able to find a suitable value to show you - if the key/argument is of any user defined type, and ToString() hasn't been overridden, then you would just get the type name - it's not going to add a lot of value.

Exceptions are mostly meant for a program to consume. Most programs wouldn't know what to do with information about the instance.
The Message property is aimed at human consumption. Other than in a debugging scenario, humans won't know what to make of Foo.

Many exception mechanisms try to serve a hodgepodge of orthogonal purposes by passing a single exception-derived object:
Letting the caller know that various specific things have happened, or that various specific problems exist.
Determining when the exceptional condition is "resolved" so that normal program flow can continue.
Providing an indication of what to tell the user of the program
Providing information which could be logged to allow the owners of a system to identify problems, when a secure log is available
Providing information which could be logged to allow the owners of a system to identify problems, but which would not pose a security risk even if secure logging is not available.
Unfortunately, I'm unaware of any exception mechanism in widespread use which can actually accomplish all five of the above, well.

Related

Why should I serialize custom exception in c#? [duplicate]

Referring to What is the correct way to make a custom .NET Exception serializable?
and Are all .NET Exceptions serializable? ...
Why should my exceptions be serializable?
Someone said "it can be considered a bug" if a custom exception defined by a third party library, is not serializable. Why?
Why are exceptions different than other classes in this regard?
Because your exceptions may need to be marshalled between different AppDomains and if they aren't (properly) serializable you will lose precious debugging information. Unlike other classes, you won't have control over whether your exception will be marshalled -- it will.
When I mean "you won't have control" I mean that classes you create generally have a finite space of existence and the existence is well known. If it's a return value and someone tries to call it in a different AppDomain (or on a different machine) they will get a fault and can just say "Don't use it that way." The caller knows they have to convert it into a type that can be serialized (by wrapping the method call). However since exceptions are bubbled up to the very top if not caught they can transcend AppDomain boundaries you didn't even know you had. Your custom application exception 20 levels deep in a different AppDomain might be the exception reported at Main() and nothing along the way is going to convert it into a serializable exception for you.
In addition to Talljoe's answer, your exceptions may be passed across Web Services as well, in this case the exception needs to be serializable/deserializable so it can be turned into XML and transmitted by the Web Service
I think that the default for all classes should be Serializable unless they contain a class that is explicitly not serializable. It's annoying to not be able to transfer a class just because some designer didn't think about it.
The same thing with "Final", all variables should be "Final" by default unless you specifically say that they are "Mutable".
Also, I'm not sure it makes sense to have a variable that is not private.
Oh well, need to design my own language.
But the answer is, you don't know how your exception will be used and they are assumed to be able to be thrown across remote calls.
Another place where objects required to be serializable is Asp.Net Session.
We store last exception in Session and not serializable exceptions needs extra translation to store their details as serializable( specifying original exception as inner doesn't help)

Making use of the ValidationException class

I have a situation where one of our developers wants to put a standard in place where we throw System.ComponentModel.DataAnnotations.ValidationExceptions in all our apps moving forward. An example would be that a user enters bad data into a form and our business logic layer throws a ValidationException which is handled at the calling layer.
However, I'm worried that this exception class is being used out of context and that one day we'll using some Dynamic Data Controls which make use of this exception and it will be difficult to tell the difference between when he's making use of the ValidationException vs times that the Dynamic Controls raise the exception.
We already use a custom exception class called something like "OurCustomException" and I think it would be better to just subclass off of that and create a OurCustomValidationException class. This way exceptions of different types can be clear cut.
Any opinions?
... it will be difficult to tell the
difference between when he's making
use of the ValidationException vs
times that the Dynamic Controls raise
the exception.
I think this is the main point you should be looking at when making that decision.
You seem to imply that the above (not being able to distinguish your own exceptions from "platform" validation exceptions) is a bad thing. That's not necessarily the case. IF you use the ValidationException exclusively to represent validation errors, then all your code can deal correctly with both your own and platform exceptions in the same way. No need to special-case platform exceptions from custom ones.
This is a win in my opinion. If you have both CustomException and ValidationException going back up to your toplevel layer for the same reasons, you'll have to repeat some logic one way or another. That's a bad thing (more maintenance, more chances of bugs creeping in).
So my opinion is that using the platform ValidationException is probably a good way to do it as long as you use it strictly for propagating validation problems.
Also think about the case where you would be giving/selling parts of your code to a third party (say it's real cool and you make a product out of it). It would probably be easier for the third party if your module throws "standard" exceptions (they can integrate it easily) rather than having to special-case all of his interface code for your module. Again, this is only valid if you stick with cases where a standard module would throw ValidationExceptions.
Lets look at it the other way around. You say:
our business logic layer throws a ValidationException
This is why I put strictly and exclusively above. You need to make sure you agree on what a validation error is. Lets look at two hypothetical problems:
"abc" is not a valid number
insufficient funds for this operation
For 1., the problem is simple/expected input validation error.
But in my opinion, 2. is not. It's a business logic problem. You could call it a validation issue (in the transaction, before the debit, you "validate" whether there are sufficient funds available) but I'd say its semantically very different.
I would advise not to put these two types of errors in the same exception "bag" as they have very different meanings, and may (often) lead to different application flow logic. (With the above two examples, 1. should keep the user on the very same form, as would any other "typo" kind of issue, but 2. should probably get him to a page that allows him to refill his account.)
To sum it up: using a standard exception seems like a good idea to me, as long as you stick with its expected semantics.

C# explicitly defining what exceptions are thrown

In Java, you explicitly define what exceptions are thrown using the "throws" keyword. That way, anyone calling your method knows what to catch.
Is there something in C#? If not, how do I know what exceptions to catch, or how do I let others know what exceptions to catch?
Also, if I am defining an interface, is there a way to say "methodX() should throw this exception on error"?
There is nothing equivalent in C#: The Trouble with Checked Exceptions
Other than documentation, there is no way to declare an interface to say "methodX() should throw this exception on error".
C#/.net does not have checked Exceptions, they proved to be less useful in large scale systems than first thought. In a lot of projects the time to maintain the check exception specs was a lot greater than the debugging time saved by having them.
Checked Exceptions seem like a good ideal until you have methods that can take delegates or calls into object you pass in. Take a simple case, the Sort() method on a list can’t know what exceptions it will throw, as it does not know what exceptions the Compar() method on the objects being sorted will throw.
So the spec for the exceptions a method may throw must be able to include information on how exceptions are populated from pass in objects and delegates. No one knows how to do this!
However there are tools that you check if you are catching all exceptions – see Exception Hunter by Red Gate. I personally don’t see much value in these tool, however if you like checked exceptions you may find them useful. ==> Looks like Exception Hunter wasn't too useful, so Redgate discontinued Exception Hunter a long while ago:
This feature is not available in C#. You can make proper XML documentation (3 slashes ///) and state what exceptions are being thrown.
This will be picked up by the IntelliSense mechanism and will be visible for the users of the class/method before they use it.
C# does not support this. (Not that I know anyway).
What you can do is use Xml Comments so that while calling you methods this data will be shown by intellisense.
As far as I'm aware there is no throws declaration in C# you can document your method indicating that it throws an exception but no forced error handling.
C# doesn't support checked exceptions. The language designers consider checked exceptions in the way java uses them a bad idea.
Some workarounds
Let me cite this medium article: It's almost 2020 and yet... Checked exceptions are still a thing
Among the many reasons why it's a bad idea, putting the checked exceptions in the contract (interfaces):
makes it impossible to change the implementation of an interface with a different one which throws different exceptions
exposes implementation details
a change of the checked exceptions of an API interface, makes it necessary to change the whole chain of interfaces in the call stack
For example, imagine that you are implementing a repository based on SQL Server, so you expose all kind of SQL Server specific exceptions. Then you want to move it to MySQL or Cosmos BD. Of course:
the implementation can't be changed to a new one that need to throw different exceptions. Also related to this, if you have different implementations of the storage, you can't just change them by configuration, but you need to have different compilations of the code for each storage backend
this is the explanation for 1: as the interface showed the implementation details (SQL Server exceptions) know you can't just change it
if you need to make the change, prepare to change the interface at all levels, since the API that uses the database up to the lates consumer in the call stack chain.
The articles cited above includes pointers to many explanations to discourage the use of checked exceptions, included this by the creator of C#: The trouble with checked exceptions

How would you like an API to expose error handling?

This title begs for more explanation.
Basically, I'm rolling an API that wraps a web service in a nice heirarchical model. This model exposes things in the form:
var obj = MyRemoteResource.GetForId(1234, SourceEnum.ThatSource);
ApiConsumerMethod(obj.SomeProperty); //SomeProperty is lazily loaded, and often exposes such lazily loaded properties itself
... etc ...
Where many different RemoteResources* (each with many properties exist). There's really aggresive cacheing going on, and request throttling to prevent inadvertantly DOS'ing the servers (and getting the IP of the caller banned).
I've got all this code working, but I'm not doing much in the way of error handling at the moment. Basically, if the consumer of an API provides an invalid ID, the web server is down, a connection times out, or any other of a plethora of request layer errors occur an exception just percolates up when a property is accessed.
I consider this far less than ideal.
So my question is, how should I wrap these errors up so that it is convenient for a user of this API to manage them?
Some routes I have considered:
Just wrap all exceptions in some API defined ones, and document them as thrown.
Expose a static ErrorHandler class that allows a user to register notification callbacks for specific errors; falling back to the above behavior when no registration has been made for specific errors.**
Null properties on error, and set a LastErrorCode.
Each of these approachs have strengths and weaknesses. I'd appreciate opinons on them, as well as alternatives I haven't thought of.
If it impacts the discussion at all, the platform class throwing these exceptions is WebClient. Furthermore, usage of WebClient is sufficiently abstract that it could easily be replaced with some other download scheme if needed.
*Which is to say, many different classes
**This would be... wierd. But it maps to the global nature of the failure. This is my least favorite idea thus far.
I wouldn't implement fancy error technologies (like events and stuff like this). It's not easy to judge where and how to use exceptions, but this is no reason to implements other stuff.
When you request an object by an id which doesn't exist, what do you have to tell the caller about this? If you just return null, the client knows that it doesn't exist, there is nothing more to say.
Exceptions force the caller to care about it. So they should only be used where the caller is expected to do something special. Exception can provide the information why something didn't work. But if it is an "error" the user could also ignore, an exception is not the best choice.
There are two common alternatives to exceptions.
Use return values which provide information about the result of an action. For instance, logon could return a LogonResult instead of throwing an exception.
Write two methods, one throwing an exception, and one (Try...) returning a boolean. The caller decides if it wants to ignore the "error" or not.
Personally I believe this is entirely dependent on the context of what your API end-user is trying to do. If this is the case, you should let them decide how to handle erors.
Recently when working with CSV files (very error prone) I used an API that allowed you to define the exception behaviour. You could either ignore the error, replace by some default value/action, or pass them off to an event handler.
I really liked this approach of letting the end user decide how to handle internal exceptions, because unless your API is very specific its difficult to preempt all scenarios.
I prefer to have an exception thrown at me when something bad happens. Exceptions are (for me, anyways) the common way to tell that something went wrong, and i find it more intuitive to catch, than to check a return value for null and check another property to see what went wrong..

Which built-in .NET exceptions can I throw from my application?

If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?
See Creating and Throwing Exceptions.
On throwing built-in exceptions, it says:
Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.
and
Do Not Throw General Exceptions
If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.
Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception."
This blog entry also has some useful guidelines.
Also, FxCop code analysis defines a list of "do not raise exceptions" as described here. It recommends:
The following exception types are too general to provide sufficient information to the user:
System.Exception
System.ApplicationException
System.SystemException
The following exception types are reserved and should be thrown only by the common language runtime:
System.ExecutionEngineException
System.IndexOutOfRangeException
System.NullReferenceException
System.OutOfMemoryException
So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation).
Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).
On the subject of System.Exception and System.ApplicationException: The latter was meant to be used as the base class of all custom exceptions. However, this hasn't been enforced consistently from the beginning. Consequently, there's a controversy whether this class should be used at all rather than using System.Exception as the base class for all exceptions.
Whichever way you decide, never throw an instance of these two classes directly. It's actually a pity that they aren't abstact. For what it's worth, always try using the most specific exception possible. If there is none to meet your requirement, feel free to create your own. In this case, however, make sure that your exception has a benefit over existing exceptions. In particular, it should convey its meaning perfectly and provide all the information necessary to handle the situation in a meaningful manner.
Avoid to create stub exceptions that don't do anything meaningful. In the same vein, avoid creating huge exception class hierarchies, they're rarely useful (although I can imagine a situation or two where I would use them … a parser being one of them).
I use the ArgumentException (and its “friends”) regularly.
NotSupportedException and NotImplementedException are also common.
My advice would be to focus on two things:
Scenarios
User expectations
In otherwords, I would sit down and identify:
Under what scenarios do you want to throw exceptions.
In those scenarios, what would the users of your API expect
The answer to #1 is, of course, application specific. The answer to #2 is "what ever similar code they are already familiar with does".
The behavior that comes out of this is:
Under the scenarios that arise in your programs that also arrive inside the
framework, such as arguments being null, out of range, being invalid, methods not
being implemented, or just not supported, then you should use the same exceptions the
framework uses. The people using your APIs are going to expect that they behave that
way (because that's how everything else behaves), and so will be better able to use
your api from the "get go".
For new scenarios that don't exist in the framework, you should go ahead and invent
your own exception classes. I would say that you should prefer Exception as your base
class unless their is some other base exception that provides services you need.
Generally speaking I don't think something like "ApplicationException" will help you
much. When you start defining your own exceptions there are a few things you should
keep in mind though:
a. The primary purpose of an exception is for human communication. They convey
information about something that happened that shouldn't have. They should provide
enough information to identify the cause of a problem and to figure out how to
resolve it.
b. Internal consistency is extremely important. Making your app behave as universally
as possible under similar circumstances will make you API's users more productive.
As far as there being hard and fast rules about what you should and should not do... I wouldn't worry about that stuff. Instead I would just focus on identifying scenarios, finding the existing exception that fits those scenarios, and then carefully desining your own if an existing one doesn't exist.
You can create and throw pretty much any of them, but you generally shouldn't. As an example, the various argument validation exceptions (ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, etc) are suitable for use in application code, but AccessViolationException isn't. ApplicationException is provided as a suitable base class for any custom exception classes you may require.
See this MSDN article for a list of best practices - it refers to handling exceptions, but also contains good advice on creating them...

Categories

Resources