Is it possible to throw CUSTOM non-catchable exception? - c#

I am writing a license module (DLL) for multiple applications. This DLL will be used in applications by adding reference. One of the requirement (pass case) for this DLL is that, if license validation fails, calling application should terminate/crash. It should not gracefully shutdown; it must crash. I do not want to show message, write log etc.
DLL and applications (using this DLL) are written in DotNet 4.
Quick solution I can think of is to throw exception instead of returning value from method. But, the exception could be caught by application and purpose will not be fully served.
Workaround for this is to declare custom exception as internal in my DLL. But, this also could be bypassed by catching Exception class.
One dirty alternative I can think of is to write a code (endless recursion or something) that will throw StackOverflowException. But I am looking for something better.
Is there any way to throw custom non-catchable exception?
References:
Ref1 and Ref2 discuss about in built DotNet non-catchable exception. My question is about custom non-catchable exceptions.

Environment.FailFast is the way to go, nothing can then prevent your application from shutting down.
Keep in mind that C# libraries can be easily changed and recompiled, so you might also want to look into using obfuscators as well.

Related

C# how to log file inside a DLL?

I'm developing a DLL and I want to log some data it generates.
I wanted to use "Log4Net", but I found the problem that in a DLL I don't have an "App.config" file where I can write the XML code, so I don't know how to implement this (I'm new in this matters).
I read about "Singleton" but I saw it's better to avoid it since it has it's issues (i.e hide some visibility of the code, problems with unit tests, ...).
So my question is: How and what is the best way to create a log file for the data generated by my DLL?
A DLL - a class library - should never be logging by itself. Even the ones that are there for output - like the one containing Console or even logger code - should never decide to write their own logfile. Logging work - all output work - that is not controllable or even fully controlled by the programmer using your DLL, is just going to be vexing behavior. And you should never write something with Vexing behavior.
Logging is the job of the person using your code, not of your code. If you are writing a Library or really anything else that usually has no output (like a Windows Service), it is customary to have a wrapper project for debugging and testing.
If it is important enough it warants an Exception. If it is not important enough for a Exception - it is propably not important enough at all. It is a daunting challenge to write good Exception handling, nevermind good Exception throwing code. But there are two articles on the mater that I link very often. And I really think would help you get you on the right paths:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
They really helped me get a handle on it. And thus far they helped countless others. And their ideas are not even tied to .NET only.
The config file will be connected in running module.
It will be in exe file if it's a console application,
or in web.config in case of web application.
To log the application flow in the DLL,
Just create a Class that create and access the log text file.
In that class, declare the object LoggingClass loggingObject; and then use this instance to access the log file.
In creating object for it, you can use,
public static LoggingClass createOrGetObject()
{
return (loggingObject == null)? new LoggingClass() : loggingObject;
}
Now, just you can call this method to get the same instance that access the log file to write the log.
In this example, Log4Net is not used but works fine for logging.
You don't say who you expect to use your dll.
If it will be used by lots of other people and if the logging is useful to them, then may not want to be forced to use log4net or this may cause problems if they want to use a different version of log4net than you are using.
I have seen several dlls which use Common.Logging to avoid this issue which allows the consumers to use whichever logging package they want.
Having said that, see Configure log4net logging in dll for another possible solution.

COMException results in "Object reference not set to an instance of an object"

I'm using a proprietary chemical simulation package called "Aspen Custom Modeler." (ACM) ACM natiely has a COM interface you can use to drive it. AspenTech expects one to use Visual Basic to interact with ACM, but I, not liking VB very much, went with C#. This has caused me all manner of trouble.
My newest issue is that ACM will throw an exceptions for even simple errors that can arise in normal usage. I have a data set that fails to converge. ACM throws a COMException, STS_F_Failure. In Visual Basic I get the correct type, but in C#, I get an "Object reference not set to an instance of an object" exception for some reason.
My guess is that the Interop library does not have the correct exception types. Does anyone know a way I can get the correct types for exceptions?
The CLR will do it's best to make COM objects look like .Net objects especially with respect to exceptions. It will examine the specific HRESULT value, consult information like IErrorInfo, etc ... in order to determine the best .Net way to represent the failure.
In this case it's appearing to choose a NullReferenceException which means that it's very likely the method is returning a value that looks like E_POINTER.
Controlling this is difficult at best. The only real option you have is to generate the .Net library such that it uses HRESULT returns and not exceptions. If that's not possible, or simply not paletable, then I would advise simply catching the NullReferenceException here.
This article has a nice explanation of how this mapping occurs
http://msdn.microsoft.com/en-us/library/9ztbc5s1.aspx

How ensure that some expected action is done whenever and wherever exception occurs?

I am doing some enhancements to existing code. And now I want to log one message whenever and wherever exception occurs.
I can add that message in catch/finally block but there are hundreds of catch blocks.
Can anyone suggest better approach to have the message logged whenever exceptions occurs at any part of the code in the assembly?
Second take:
A good approach is AOP with Postsharp.
I've used in many projects.
You can define an attribute that inherits from a base one of PostSharp API which permits you to intercept any method call of the one where you place your custom attribute.
If you put that attribute in any method, you'll be able to try/catch absolutely any method body, and, in the end, control exceptions and logging them.
You can achieve the same goal with Castle Dynamic Proxy, but this is a run-time solution, since you can create proxy classes with interceptors and instantiate your classes with a factory. Obviously, this is consuming more resources.
Postsharp performs IL weaving, meaning that your interceptors will be injected in your actual code in compile-time, so, you don't loose run-time performance.
Summarizing, you can create a "LogAttribute" and place it in any method you want to log or do things if an exception happens.
This is an interesting issue when you have legacy code you have to deal with.
If you REALLY do not want to change your catch blocks, then I might suggest a workaround :
One option you got is writing aLoggedExceptionInterfaceor whatever, and implement aLogEventin it, and then audit all of your code scanning for handled exception types and redefening them by adding your interface to them.
For example you would replace IOException by LoggedIOException where the latter inherits the first, implementing the LoggedExceptionInterface on top.
Of course, this might turn out to be heavier than changing catch blocks individually;The choice is yours.
For sure, you've last-chance exception handlers.
ASP.NET has it in the HttpApplication, with the Error event (most of the times in the Global ASAX if you're not using an HTTP Module).
WPF and Silverlight have then in the Application.
And Windows Forms can use the AppDomain.UnhandledException event.
Mika Jacobi is right, this is a bad answer. Sorry for that.

nicely exception handling

In our app, we use components developed by other teams. The question was how can I define a nicely way of exception handling than this
try
{
someComponent.DoStuff();
}
catch (Exception ex)
{
textLabel= ex.Message;
}
The component has no custom exception type, maybe a nicely way to do it would be to define a component specific Exception type and wrap this somehow?
I know the question is very basic, but I am interested more in the let's say how it is good to do it. If you call another component with no custom defined exception types, how do you handle any potential exceptions in an elegant way?
Ideally you would have the component development team do this for you - how else do they expect their clients to recognize and handle errors from their component? Scoping the exceptions that a component can raise is a fundamental part of good C# design.
If that's not an option, then implementing your own wrapper on top of the component to taxonomize its failure cases sounds like a good second best, and very noble of you into the bargain.
If the third-party library is poorly documented (they don't specify the exceptions that can be thrown by each method), there are tools available that can Reflect into the code and determine the possible Exceptions that may be thrown. This can get a bit daunting (there are a surprising number of exceptions that can be thrown for any given call), but it's better in principle than catching the general Exception type. Here is one commercial product that performs this type of analysis.
When you catch an error you are able to repackage it and then throw another error, at the most basic level you may just be adding more data - but, from what you've suggested, you could also replace the generic error with a custom error that, whilst it won't overcome the limitations of the response you've got from the component, would give the code further up the call stack the opportunity to respond more appropriately.
So in terms of just adding information in the most basic manner - by throwing a new exception with some additional text whilst still passing the original exception:
catch (Exception ex)
{
throw new Exception("This is more about where the exception occurred", ex);
}
Now, if you want to define your own custom component exception you change the new Exception to new ComponentSpecificException adding data as necessary to the constructor but never forgetting to set the inner exception. Exceptions also have a data collection of key, value pairs into which you can insert more information (by creating the exception, adding the data and then doing the throw).
That's all fairly generic - working forward from there, where you can't necessarily anticipate all the exceptions you have to handle you don't try - you set up logging so that you know when you've got a generic exception i.e. one that hits the final catch - and then over time add exception specific catches above the generic to provide more appropriate responses or, at the very least, package up the error into less general custom exceptions.
Not sure I've explained that very well - but the notion is that as its difficult to anticipate every possible error you want to have a strategy to develop your application in a systematic fashion as you discover new exceptions.
Assuming you want to catch every type of exception, this solution looks fine to me.
Either from your knowledge of using the component, or by using something like Reflector to analyze the compiled component, what possible exceptions can this component throw? Would providing exception handlers for these allow you to provide better feedback to you users?
The only reasonable (much less "elegant") way to handle exceptions is to log them if you can't recover from them.
Then notify the user there was a problem and offer them the chance to try again (if it's an interactive program).
If your application is exclusively for .NET developers, go ahead and show them the exception message (though Exception.ToString is better, since it includes a stack trace). Otherwise, don't display exception messages in your user interface - that's a security hole and will only confuse your users.

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