Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have quite a large class that uses many more classes. It uses external resources (database, files etc.) and a few exceptions might happen.
As I learned, sometimes it is preferable to use the event of UnhandledException instead of putting try-catch blocks everywhere.
However, my class is just one of many other classes and the aforementioned solutions work at the application-level.
Can I somehow narrow it down to get fired only if the exception fired in this class and the other unhandled exceptions don't get caught?
Using AOP seems like a good way but I'm not sure.
I'm not sure if I entirely understand your question, but allow me to try to answer it anyway:
You're asking if it's possible to load your class in such a way that it knows which of the exceptions it might generate, are being handled in the class that's loading the dll? This seems impossible, simply because of the calling hierarchy. What I would suggest is that you document which exceptions may be thrown in your classes, using this mechanism:
/// <exception cref="ArgumentOutOfRangeException">Thrown if argument is greater than the size of the array.</exception>
That way your calling classes can be better prepared to handle the exceptions, and know more or less which possible exceptions aren't being handled.
Another approach is to encapsulate your code in try-catch blocks, and use the fact the more specific exceptions are handled first. You can then handle the scenarios you can resolve programmatically, and then catch the generic Exception last to ensure your program remains stable even if underlying classes fail catastrophically.
Unfortunately I don't see how you're going to tell your called dll, which of the exceptions it might throw are being handled.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In C# I need to catch an XMLException but I also have to differentiate it, because it can be either Xml_InvalidRootData or Xml_UnexpectedEOF.
How can I achieve this?
Those strings I can only see in debugger with an alias of "ResString".
But I want to have multi-culture solution, so string comparison is something I want to avoid as much as possible.
HResults are the same.
If you take a look at
https://referencesource.microsoft.com/#System.Runtime.Serialization/System/Xml/XmlExceptionHelper.cs
you'll see that throughout, there is a lot of work done to get a (possibly localized) error string, which is then the only argument to new XmlException.
As you correctly note, if you need to distinguish between different exception conditions to make some programmatic response, this is a whole lot of no help.
Since you do not want to examine the strings -- and that is a reasonable choice -- your best bet is probably to write your own XML parser that has the output you desire.
Consider the design of such a parser carefully. The output that you want is not the structured XML, but rather a detailed report explaining why it is not legal XML. Exceptions are a mechanism for handling exceptional situations; the designers of the XML parser considered malformed XML to be an exceptional situation; they thought this scenario should almost never happen. Since it almost never happens, and since when it does happen, there's nothing the program can do about it, there is no incentive to produce a detailed report that allows programmatic decisions to be made on the basis of what errors were detected.
But that is apparently not your situation; you have the opposite situation of the designers of the XML parser. You care about the error, and you wish to do something different depending on different errors, so the output of your parser should be the error report, not the XML syntax tree. It should not throw exceptions at all, because in your scenario, a malformed XML document is not exceptional; you expect it.
XML is not a particularly difficult language to lex and parse (provided you are not also trying to solve the problem of "is this document a valid instance of this schema?", which is a harder problem) so it should not take you long to produce an error-detecting lexer and parser, particularly since you have the source code of existing XML parsers to guide you. Good luck!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
When configuring UseScheduledRedelivery in a mass-transit consumer. what is the best practice for what should be handled.
Is handling Exception overkill? and is there a list of exceptions that can proberbly be recovered from?
Redelivery is second-level retry. It means that it handles exceptions that are not recovered by first-level retry (retry policies).
Basically, you probably want to retry everything except exceptions that are caused by your message data. However, even null reference exceptions can be subject of retries. For example, you have a database and you try to get a record and get null. This can be because the record is not there yet, but it will come later since there is a message in the queue to create it. So, race conditions can lead to such exceptions.
Second-level retries, however, are different. You want to use them to overcome, for example, issues with resource starvation (busy database or something). These exceptions are very specific, like network timeout exception or database timeout exception. But there is no "list", you need to look at your system design to decide where you apply first-level retries and where you use second-level retries, and which exceptions are handled by those.
We use retries for all exceptions and redelivery for a very small number of exceptions and not in all services. Usually we redeliver after getting database timeout.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
The Managed Threading Best Practices page states:
Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility of threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests. Furthermore, if static data are synchronized, calls between static methods that alter state can result in deadlocks or redundant synchronization, adversely affecting performance.
I understand all the rest except for the one sentence that is in bold.
How would you do this without essentially changing the field from a static one to an instance one? Isn't that saying, "In a server scenario, avoid using static class-level members as much as you can?"
If it isn't, could you please provide an implementation of the design pattern it is alluding to?
How would you do this without essentially changing the field from a static one to an instance one?
No one can possibly answer this question without knowing why you thought that putting something in a static field was a good idea in the first place.
Isn't that saying, "In a server scenario, avoid using static class-level members as much as you can?"
No. To be clear, that is a good idea. But that's not what this sentence is trying to communicate. It is saying if you have a problem that you think could be solved by making a static method that modifies static state, then maybe you should consider finding some other way to solve the problem.
If it isn't, could you please provide an implementation of the design pattern it is alluding to?
Design patterns exist to solve problems. You haven't said what problem you're solving, so it's impossible to recommend a pattern.
Look, suppose you're planning on constructing a building on sand, and I tell you that only fools build on sand, and you then say OK, give me a design for a building that still meets my needs, but not built on sand. I don't know what your needs are and I don't know why you thought that building on sand was a good idea in the first place, so no, I can't do that. But that does not change the fact that only fools build on sand.
Are you thinking of modifying static state in a multithreaded server scenario? That's a really foolish thing to do. Find another way to do whatever you want to do. How? I haven't the faintest idea; I don't know what you're trying to do. But that doesn't change the fact that you're unlikely to be successful by modifying static state on a multithreaded server.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In the code base I'm working on there are several examples of
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
According to the MSDN documentation (http://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx) this is redundant because createDirectory won't overwrite an existing directory.
This could be seen as making the code clearer, as it's not obvious from the .CreateDirectory(dir) method that this is the behaviour.
On the flip side, this is code bloat and keeping it around (even adding it to a library/utility class) has its issues (means you have to read/maintain more lines of code for example).
What's considered best practice here?
It may look redundant, but I can see a reason why someone decided to go that way.
The main difference is:
Directory.Exists() returns just bool
Directory.CreateDirectory() returns DirectoryInfo
So even when the directory exists, there is additional work performed to get that DirectoryInfo instance, which may not be necessary at all.
Another thing that come up is the fact, that you have to know that Directory.CreateDirectory does not override the directory if it exists! With additional Directory.Exists call even when someone doesn't know that he can really easily figure out what's going on with this piece of code.
And I don't think there is a best practice here.
Personally, I would normally remove the redundant code.
This could be seen as making the code clearer, as it's not obvious from the .CreateDirectory(dir) method that this is the behaviour.
In general, I'd argue that would be better served by a comment, rather than a redundant code path. Adding extra code to avoid a lack of knowledge seems like a weak reason to include the check.
That being said, there is a potential (very minor) performance gain in avoiding the call to CreateDirectory, as that method will construct a DirectoryInfo instance. In practice, this is most likely "noise" (as IO calls tend to be relatively expensive anyways), so its not something I would factor into the equation unless it proved to be a measured problem.
A race condition could cause the creation of a directory to fail even if the preliminary check has passed.
Therefore I consider this code as incorrect and I dissuade you from using it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Imagine you're writing a library. Say, this library is going to be used in 24/7 server application. There are some unmaneged resourses, wrapped in your public API, so you implement Disposable pattern( you may even implement finalizers)
Normally, you would use using statement to free the unmanaged resources. But you are writing just a library, not a final application. What if another programmer 'forgotten' to call Dispose()? You are going to get resource leak in your lib!
We could rely on finalizers, but there is no guarantee that a finalizer would ever been called.
So, is there a way to guarantee that somehow the unmanaged resources would be freed? Any ideas?
There is no solution except documenting your classes. Write explicitly in your documentation how your classes are meant to be used (i.e. they are meant to be disposed at the earliest possible time, possibly with using, or with an explicit call to Dispose).
You are no more responsible for memory leaks if your consumer does not properly dispose its object than industrials are responsible for the pollution if people trash their garbage in the wild.
You could hope that the server application has code analysis rule CA2213: Disposable fields should be disposed enabled.
Otherwise I don't know if there is a way to guarantee that they call your Dispose() method.