Throwing a Win32Exception - c#

I've been writing a lot of code recently that involves interop with the Win32 API and have been starting to wonder what's the best way to deal with native (unmanaged) errors that are caused by calls to Windows API functions.
Currently, the calls to native functions look something like this:
// NativeFunction returns true when successful and false when an error
// occurred. When an error occurs, the MSDN docs usually tell you that the
// error code can be discovered by calling GetLastError (as long as the
// SetLastError flag has been set in the DllImport attribute).
// Marshal.GetLastWin32Error is the equivalent managed function, it seems.
if (!WinApi.NativeFunction(param1, param2, param3))
throw new Win32Exception();
The line that raises the exception can be equivalently rewritten as such I believe:
throw new Win32Exception(Marshal.GetLastWin32Error());
Now, this is all well in that it throws an exception appropriately containing the Win32 error code that was set as well as a (generally) human-readable description of the error as the Message property of the Exception object. However, I have been thinking that it would be advisable to modify/wrap at least some, if not all, of these exceptions so that they give a slightly more context-oriented error message, i.e. one more meaningful in whatever situation the native code is being used. I have considered several alternatives for this:
Specifying a custom error message in the constructor for Win32Exception.
throw new Win32Exception(Marshal.GetLastWin32Error(), "My custom error message.");
Wrapping the Win32Exception in another Exception object so that both the original error code and message are retained (the Win32Exception is now the InnerException of the parent exception).
throw new Exception("My custom error message.",
Win32Exception(Marshal.GetLastWin32Error()));
The same as 2, except using another Win32Exception as the wrapper exception.
The same as 2, except using a custom class derived from Exception as the wrapper exception.
The same as 2, except using a BCL (Base Class Library) exception as the parent when appropiate. Not sure whether it's even appropiate to set the InnerException to the Win32Exception in this case (perhaps for a low-level wrapper but not a higher-level/abstracted interface that doesn't make it obvious that Win32 interop is happening behind the scenes?)
Essentially what I want to know is: what is the recommended practice on dealing with Win32 errors in .NET? I see it done in open-source code in all sorts of different ways, but I was curious whether there were any design guidelines. If not, I'd be interested in your personal preferences here. (Perhaps you even use none of the above methods?)

This isn't really specific to Win32 exceptions; the question is, when should two different error cases be identified by two different Exception-derived types, and when should they throw the same type with different values stored inside it?
Unfortunately this is impossible to answer without knowing in advance all the situations your code will be called in. :) This is the problem with only being able to filter exceptions by type. Broadly speaking, if you have a strong feeling that it would be useful to treat two error cases differently, throw different types.
Otherwise, it is frequently the case that the string returned by Exception.Message just needs to be logged or displayed to the user.
If there is additional information, wrap the Win32Exception with something more high-level of your own. For example, you're trying to do something to a file, and the user you're running under doesn't have permission to do it. Catch the Win32Exception, wrap it in an exception class of your own, whose message gives the filename and the operation being attempted, followed by the inner exception's message.

My view has always been that the appropriate way to handle this depends on the target audience and how your class is going to be used.
If the caller of your class/method is going to realize that they are calling into Win32 in one form or another, I would use option 1) you have specified. This seems the most "clear" to me. (However, if this is the case, I'd name your class in a manner that makes it clear that the Win32 API is going to be used directly). That being said, there are exceptions in the BCL that actually subclass Win32Exception to be more clear, instead of just wrapping it. For example, SocketException derives from Win32Exception. I've never personally used that approach, but it does seem like a potentially clean way to handle this.
If the caller of your class is going to have no idea that you're calling into the Win32 API directly, I would handle the exception, and use a custom, more descriptive exception you define. For example, if I'm using your class, and there's no indication that you're using the Win32 api (since you're using it internally for some specific, non-obvious reason), I would have no reason to suspect that I may need to handle a Win32Exception. You could always document this, but it seems more reasonable to me to trap it and give an exception that would have more meaning in your specific business context. In this case, I might wrap the initial Win32Exception as an inner exception (ie: your case 4), but depending on what caused the internal exception, I might not.
Also, there are many times when a Win32Exception would be thrown from a native call, but there are other exceptions in the BCL that are more relevant. This is the case when you're calling into a native API that isn't wrapped, but there are similar functions that ARE wrapped in the BCL. In that case, I would probably trap the exception, make sure that it is what I'm expecting, but then throw the standard, BCL exception in its place. A good example of this would be to use SecurityException instead of throwing a Win32Exception.
In general, though, I would avoid option 2 and 3 you listed.
Option two throws a general Exception type - I would pretty much recommend avoiding that entirely. It seems unreasonable to wrap a specific exception into a more generalized one.
Option three seems redundant - There's really no advantage over Option 1.

Personally I would do #2 or #4...Preferably #4. Wrap Win32Exception inside your exception which is context sensitive. Like this:
void ReadFile()
{
if (!WinApi.NativeFunction(param1, param2, param3))
throw MyReadFileException("Couldn't read file", new Win32Exception());
}
This way if somebody catches the exception, they will have a pretty good idea where the problem occurred. I wouldn't do #1 because it requires the catch to interpret your text error message. And #3 doesn't really give any additional information.

Related

Intentionally cause a fatal exception

I need to create a fatal exception on demand, using C#. While I have done this unintentionally enough times, now I need to, I can't find a simple way.
It's easy enough to cause a null reference error or divide by zero etc., but I need something which will CTD without giving the option to continue.
Thanks for your help.
Don't use an exception to accomplish this, it has too many side-effects. Including not terminating the program at all, whether an unhandled exception ends the program is a CLR policy that can be changed. Both by a custom CLR host and still exposed today by the legacyUnhandledExceptionPolicy config attribute.
The most reliable way to instantly abort a program, without any events getting fired and without any cleanup (including not running finalizers) is Environment.FailFast().
IMHO I prefer a milder approach. I create a custom Exception that I call FatalException. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions. That way when I call methods that throw FatalException, I simply do a try-catch around the call and catch (FatalException fe). I usually re-throw as necessary to get back to parent form which also has a the final catch for the FatalException exception and then log it (I use Log4Net), show a messagebox as to the reason for the Fatal situation and call my overridden Dispose() method and exit the application gracefully. Obviously this becomes more difficult the deeper your nested calls. The extra work is worth the extra grace to me. If this becomes a standard in your application, you will understand it when you encounter it and ensure that you don't break it. I put my Custom Exceptions in a DLL library. If your code is in a library, this approach still works because the Exceptions are also in a library they can be shared by both another library and the main application. This means your library can throw a FatalException as well, although the reasons for doing so should be few a far between.

Exception handling: user defined exception benefits

My exception handling skills are very primary and I am always very confused about the way I should use them, not so much of the how/syntax. I am currently using C# (if there would be different things applicable to it).
My question is that what are the benefits of creating your own Exception class while developing an application? In comparison to throwing a standard Exception class exception. Basically what is a healthy practice of exceptions in your application.
Or if not benefits, then disadvantages?
By creating your own exceptions you can often create a more meaningful message (or more application specific type of message) for the end user, while still wrapping the original message, so as not to lose any useful information.
There is a great book by Bill Wagner that covers some reasoning about when you should or should not create your own exceptions along with some good practices for exception handling in general. Here is a small excerpt:
Your application will throw exceptions -- hopefully not often, but it
will happen. If you don't do anything specifc, your application will
generate the default .NET Framework exceptions whenever something goes
wrong in the methods you call on the core framework. Providing more
detailed information will go a long way to enabling you and your users
to diagnose and possibly correct errors in the field. You create
different exception classes when different corrective actions are
possible and only when different actions are possible. You create
full-featured exception classes by providing all the constructors that
the base exception class supports. You use the InnerException property
to carry along all the error information generated by lower-level
error conditions.
If there is a specific type of problem unique to your application that will call for a unique recovery strategy at a higher level in your application, you should create your own exception type so you can recognize and recover from that sort of problem optimally.
If the error is more of a "the caller did something wrong" variety, use the standard exception classes.
If you think your library is going to be long-lived and valuable, I would err on the side of creating your own exception classes, so that future users of your library can fashion their own recovery strategy.
Sometimes you want to do diffrent things for diffrent types of error, for example if a user inputs bad data it dosent make sence to crash the whole application and email the administrator. It would make sence to do that for a more serious exeption such as a stack overflow. You would then impliment diffrent catches depending on the type of error.
If a method is documented as throwing some particular class of exception in some particular circumstance, it should ensure that there's no way any exception of the class can bubble up through it in other circumstances. In many cases, the most practical way to ensure this may be to create a custom exception class.
Actually, I would regard much of the exception hierarchy as being pretty useless, and would suggest focusing on a fairly small number of exceptions, from which nearly all good exceptions should derive.
CleanFailureException -- The indicated operation could not be performed for some reason, but has not altered any object's state. There is no reason to believe any object's state is corrupt except to the extent implied by the operation's failure. This should be the type of exception thrown by a DoSomething method if a TrySomething method would return False. May in some cases be wrapped in a more severe instruction, if a failed operation leaves one or more objects in partially-altered or inconsistent states.
StateDisturbedException -- The indicated operation could not be completely performed for some reason, but may have been partially performed. The object on which an action was being performed has a state which complies with its own invariants, but may or may not comply with caller's expectations of it. Caller may attempt to use the object only after examining it and making sure it complies with expectations (changing it as needed). Alternatively, this exception should be caught at the point where the target object would no longer exist, and then wrapped in a CleanFailureException.
TargetStateCorruptException -- The indicated operation could not be performed because the particular object being acted upon is corrupt, but there is no particular reason to expect that corruption extends outside the object. This exception should be caught at the point where the target object would no longer exist, and then wrapped and replaced with CleanFailureException.
ParentStateCorruptException -- The indicated operation could not be performed because some object which the target's documentation would regard as a "parent" object is corrupt. Catch at the level where the corrupt parent objects would no longer exist, then wrap in a "CleanFailureException".
SystemOnFireException
While it may be nice to have exception names that indicate the nature of what went wrong, from a catching perspective what matters is whether one can safely catch and resume. Any exception hierarchy should focus on the latter issues, rather than the former. If the goal is to inform people of what went wrong, that should be done in Exception.Message.
The main benefits are to add information, so exceptions are more meaningful and thus allowing to catch exceptions that are specific to your application.
Throwing an exception is actually a more expensive operation than quietly failing, such as returning a bool. This question highlights what I mean:
How much more expensive is an Exception than a return value?
If you're writing something that you anticipate other developers are going to be using in their own project, then sure, an exception could be useful for them to make sure they're using your code right. Otherwise, if you're just using it within your own codebase, I would make sure to quietly fail.
One example where custom exceptions work well is when you are expecting external applications to interface with your project.
For example, if you had a small project that sends out an email it might make sense to throw a custom 'TooFewRecipients' error if you had a hard limit on the minimum number of recipients that must be emailed.
Custom exceptions will in general inherit from System.Exception
Remember that Exceptions should only be used for exceptional cases which your project can't handle in any other way, and they should be understandable enough to aid a 3rd party developer understand the issue. There is more information at MSDN

Cost of Custom Exceptions

I've read that throwing exceptions is an expensive operation. However, doesn't creating your own exceptions make your code more expressive and readable?
Some of my coworkers suggest that you should just use System.Exception and insert your custom text into the message instead of creating a new custom exception.
I'm interested in other opinions. Appreciate any suggestions.
Do not throw System.Exception. Ever.
The problem with it resides in the calling code. It is a bad practice to catch the general Exception object for many reasons. If you throw an instance of the Exception base class, then calling code has no choice but to catch Exception if they want to handle it. This forces the calling code to use a bad practice.
Also, the calling code has no reliable means of distinguishing what the exception was, if all it gets is Exception.
It is typically best to use one of the pre-defined exceptions if any are applicable (ArgumentException, InvalidOperationException, etc.). If none correctly describe the situation, then a custom exception class is a perfectly good way to go.
It's the overhead of throwing an exception itself (creating the object, walking the stack, etc.) that's costly. Making your own exception class adds almost no overhead, so if you're going to throw an exception, don't make it new Exception("message")!
Exceptions aren't meant to be read by people (though their messages and stack traces are read by people), they're meant to be read by code. If there's something your code can do in response to a custom exception, by all means go for it. But the exception is just destined to be logged, there's no point to making a custom one.
The overhead of custom exceptions is that they're another thing to maintain and test. If an existing exception is suitable, use that instead. (E.g., ArgumentNullException instead of ZipCodeNullException.)
If there's any reason for your exception to be caught and handled differently from standard Exceptions, then you should create your own class.
If there's any reason for your exception to take different arguments (e.g. to produce a specially-formatted message based on a set of arguments that you're often likely to have), then you should create your own class.
In any other case, you're safe just using Exception. Generally speaking, it doesn't really cost any more to instantiate or throw a custom exception than a standard one, at least not compared with the expense of throwing an exception in the first place. Exceptions, by definition, should be exceptional, and therefore performance during the throwing of an exception is a non-issue. The point is to have all the information you need when the time comes to look at why that exception was thrown.
You should never throw a System.Exception, because then the only way to catch is is by catch(System.Exception). It's very bad practice to catch a blanket exception like that. You should catch specific exceptions, which give you a way to properly handle it without crashing the software. By generating custom exceptions, you give yourself a way to potentially recognize and recover from them.
For example, if your code means to open a file, and you get an unknown exception, how do you recover from it? However, if you catch a specific File Not Found exception, that is much easier to recover from. You can tell the user definitively that the file doesn't exist.
I don't see a reason to believe that custom exceptions are any more expensive than the built-in ones.
"Expensive" is a relative term and - as the name already suggests - an exception should be an exception, so it will probably not affect the performance of your code. The cost of throwing an exception is - as far as I know - independent of the type of the exception, so you should not restrict yourself to System.Exception.
But most important: http://c2.com/cgi/wiki?PrematureOptimization
I prefer to use the most appropriate built in exception, and if that doesn't already exist, derive my own from System.ApplicationException.
I wouldn't recommend throwing System.Exception with a custom message.
Your coworker is talking nonsense. Throwing an exception is the same cost regardless of the class.
And to be honest, all this talk of "expensive" exceptions - yes they are more expensive than a null check or some such, so don't ever use them as a replacement for some sanity check, but they should be encouraged where they make sense (like IOException for example, that's an excellent use case for them - problems with I/O are an exceptional case and they usually must be handled outside of normal program flow).

When to use a user defined Exception and some good examples/best Practices?

I would assume that most User-defined Exceptions are for Business Logic level exceptions, but what are some good reasons to use a User-Defined Exception and what are some good examples?
Is a user-defined exception's only advantage that you can define a consistent Error Message?
What logic can be written inside exceptions to make them truly more useful?
After all, can't you just do this: throw new Exception("Some Error Message");
Having user-defined exceptions is useful because it allows you to handle different kinds of errors in specific ways. Why does .NET define so many different types of exceptions if they could just throw all exceptions as System.Exception with a different text message? The reason that there are different types of exceptions in .NET is that you can catch individual types of errors and handle them differently. That's the same reason you would define your own user exceptions - so that you can provide a different response based on the type of exception that occurred.
You can also create user-defined exceptions that include additional data. For example, you could define a severity level based on an enum, an integer error code or anything else that might be useful to the calling program to identify what went wrong. As for logic to include in exceptions, I generally just try to report what went wrong and leave the logic (what to do about the error) to the calling program. In some cases, I have the exception code automatically write the error to a log file if it has exceeded a certain severity level (e.g. warnings are thrown but only critical errors are written to the log file).
You should create very few user-defined exceptions. They should only be used if someone is going to catch the exception and do something specific with it. If throwing your exception instead of InvalidOperationException is not going to make the code behave differently, then throw InvalidOperationException.
There are quite a lot of Exceptions already in the .NET framework, which you should use if you can find one that could be used for your exceptional circumstance.
For example, in my configuration classes (which are normally wrappers around the ConfigurationManager) I throw ConfigurationErrorsException when ever a value can't be parsed correctly.
When parsing custom values from text or something else that requires a specfic format and the parsing fails, I throw a FormatException
However if my BankAccount object doesn't have enough money in it for me to withdraw £10 then I'll write and throw InsufficentFundsException because then that way I can handle that specific error case, if it ever occurs.
Hope this (somewhat) helps.
No, they are not only for messages. You can look for User defined ones in the exception list of a catch block.
catch(UserDefinedException){}
catch(Exception){}
You can use User Defined Exceptions anytime you want to look for something specific that occurs. Maybe a Client ID is out of a specified range and you want to look for that specifically. Instead of having to parse the error message (which can be a pain, and is prone to errors, like if the message changes later down the road), you have an exception you use and you know that somewhere else in the code is specifically telling you "Hey this happened. You need to be aware of it."
User defined exceptions can be used within a component to allow consumers of the component the ability to catch them with a greater level of granularity then the catch (Exception) block. This will provide the component consumer with the ability to perform different tasks, based on which exception has been thrown. User defined exceptions should only really be created when there is a real expectation that consumers will use them to differentiate in this way.
You can also add properties to store additional meta-data with a user-defined exception, such as an error code (for example when calling an unmanaged API). This is more user-friendly than simply putting stuff into the Data property of the Exception object.

Do you write exceptions for specific issues or general exceptions?

I have some code that gives a user id to a utility that then send email to that user.
emailUtil.sendEmail(userId, "foo");
public void sendEmail(String userId, String message) throws MailException {
/* ... logic that could throw a MailException */
}
MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.
My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.
Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc.
My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).
Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
In my code, I find that MOST exceptions percolate up to a UI layer where they are caught by my exception handlers which simply display a message to the user (and write to the log). It's an unexpected exception, after all.
Sometimes, I do want to catch a specific exception (as you seem to want to do). You'll probably find, however, that this is somewhat rare and that it is indicative of using exceptions to control logic -- which is inefficient (slow) and often frowned upon.
So using your example, if you want to run some special logic when the email server is not configured, you may want to add a method to the emailUtil object like:
public bool isEmailConfigured()
... call that first, instead of looking for a specific exception.
When an exception does happen, it really means that the situation was completely unexpected and the code can't handle it -- so the best you can do is report it to the user (or write it to a log or restart )
As for having an exception hierarchy vs exceptions-with-error-codes-in-them, I typically do the latter. It's easier to add new exceptions, if you just need to define a new error constant instead of a whole new class. But, it doesn't matter much as long as you try to be consistent throughout your project.
I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.
An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).
This way you get the advantages of both, you don't have throw-clauses like:
throws SpecificException1, SpecificException2, SpecificException3 ...
a general
throws GeneralException
is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
#Chris.Lively
You know you can pass a message in your exception, or even the "status codes". You are reinventing the wheel here.
I have found that if you need to have CODE deciding what to do based on the exception returned, create a well named exception subclassing a common base type. The message passed should be considered "human eyes only" and too fragile to make decisions upon. Let the compiler do the work!
If you need to pass this up to a higher layer through a mechanism not aware of checked exceptions, you can wrap it in a suitable named subclass of RuntimeException (MailDomainException) which can be caught up high, and the original cause acted upon.
It depends on what your application is doing. You might want to throw individual exceptions in cases like
The application is high availability
Sending e-mail is particularly important
The scope of the application is small and sending e-mail is a large part of it
The application will be deployed to a site which is remote and you will only get logs for debugging
You can recover from some subset of the exceptions encapsulated in the mailException but not others
In most cases I would say just log the text of the exception and don't waste your time granularizing already pretty granular exceptions.
I think a combination of the above is going to give you the best result.
You can throw different exceptions depending on the problem. e.g. Missing email address = ArgumentException.
But then in the UI layer you can check the exception type and, if need be, the message and then display a appropriate message to the user. I personally tend to only show a informational message to the user if a certain type of exception is thrown (UserException in my app). Of course you should scrub and verify user input as much as possible further up the stack to make sure any exceptions are generated by truly unlikely scenarios, not as a filter for malformed emails which can easily be checked with a regex.
I also wouldn't worry about the performance implications of catching an exception from user input. The only time you are going to see performance problems from exceptions is when they are being thrown and caught in a loop or similar.
Instead of using exceptions, I tend to return a list of status objects from methods that may have problems executing. The status objects contain a severity enum (information, warning, error, ...) a status object name like "Email Address" and a user readable message like "Badly formatted Email Address"
The calling code would then decide which to filter up to the UI and which to handle itself.
Personally, I think exceptions are strictly for when you can't implement a normal code solution. The performance hit and handling restrictions are just a bit too much for me.
Another reason for using a list of status objects is that identifying multiple errors (such as during validation) is MUCH easier. After all, you can only throw one exception which must be handled before moving on.
Imagine a user submitting an email that had a malformed destination address and contained language that you are blocking. Do you throw the malformed email exception, then, after they fix that and resubmit, throw a bad language exception? From a user experience perspective dealing with all of them at once is a better way to go.
UPDATE: combining answers
#Jonathan: My point was that I can evaluate the action, in this case sending an email, and send back multiple failure reasons. For example, "bad email address", "blank message title", etc..
With an exception, you're limited to just percolating the one problem then asking the user to resubmit at which point they find out about a second problem. This is really bad UI design.
Reinventing the wheel.. possibly. However, most applications should analyze the whole transaction in order to give the best possible information to the user. Imagine if your compiler stopped dead at the first error. You then fix the error and hit compile again only to have it stop again for a different error. What a pain in the butt. To me, that's exactly the problem with throwing exceptions and hence the reason I said to use a different mechanism.
I tend to have less Exception types, although it's not really the OO way to do it. Instead I put an enum to my custom Exceptions, which classifies the Exception. Most of the time I have a custom base Exception, which holds on to a couple of members, which can be overridden or customized in derived Exception types.
A couple of months ago I blogged about the idea of how to internationalize Exceptions. It includes some of the ideas mentioned above.
While you can differenciate the code execution looking the exception don't matter if it's done by the "catch exceptionType hierarchy mode" or by "if(...) else...exception code mode"
but if you are developing software wich is going to be used by other people, like a library i think it's usefull create your own exception types to notice the other people that your sofware can throw other exceptions than the normal ones, and they better catch and resolve them.
When i use a library and their methods simply launch an 'Exception' i allways wonder: What can cause this exception?, how must my program react?, if there is a javadoc maybe the cause will be explained, but mustly of times there is not a javadoc or the exception is not explained. Too much overhead witch can be avoided with a WellChossenExceptionTypeName
It depends on whether the code that catches the exception needs to differentiate between exceptions or whether you are just using exceptions to fail out to an error page. If you need to differentiate between a NullReference exception and your custom MailException higher up in the call stack, then spend the time and write it. But most of the time programmers just use exceptions as a catch all to throw up an error on the web page. In this case you are just wasting effort on writing a new exception.
I would just go by
throw new exception("WhatCausedIt")
if you want to handle your exceptions, you could pass a code instead of "WhatCausedIt" an then react to the different answers with a switch statement.

Categories

Resources