Save call stack [duplicate] - c#

This question already has answers here:
How to print the current Stack Trace in .NET without any exception?
(7 answers)
Closed 3 years ago.
Short version: Is there a way to somehow save the current call stack and store it for later?
Context: This issue seems like it would be so common that I might just be missing the correct search terms.
A certain class needs to read a variable from a server. I just send the request to the server using an API and at some point in the future a separate thread will get the reply and call some follow up method on the original caller class.
Simple enough, but there might be errors: either the variable I'm trying to get doesn't exist, is an incorrect type or something else. In those cases the best I can output to a debug log can be something like: "Unable to find variable X" and a stack trace of the worker. What I would really like having is a stack trace of the original caller, that I can store somewhere and print out in case there is an error so I can narrow down issues instead of having to hunt down which caller it is.

Environment.StackTrace would give you the current stack trace.

Related

Is it a bad idea return a tuple instead of throw an exception? [closed]

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 2 years ago.
Improve this question
I have a method, that always has to return an object of type MyType. If it returns null it is because I don't have the needed information to return a value.
So I was thinking that a posibility it is to throw an argument exception if I don't have the needed information.
Another solution, it is to return a tuple, first item null or the object as result. The second item a string, null if I can return the value or a string with the reason why it is null.
I was consideration this second option, because I guess it is more versatile, who calls this method, if get a null, can know the reason of why it is null and don't need to handle the exception, that requieres more code. Also, if it is called in the UI layer, it can tell the user what information it is needed.
An exception it is more expensive if it is thrown, and also, from a point of view, I considerate the exception the way to handle something that I can't control in another way, but in this case I can know in advance if I have the needed information or not from the user, so it is not something unexpected like if I try to load a file and the file doesn't exist, for example, or try to connect to a network resource and the network is down.
Also, argument exception it is a generic exception, if I want to show to a user a understanding message but also I want a more detailed message for the developer, it is more complex code.
So I was wondering if really it is a bad idea to return a tuple or it is better to throw an exception.
I think a touple can be very usefull, because it can return the value of the method, but also can provide aditional information in another items.
This is a variant on the Return codes vs exception discussion.
I would recommend using a specialized type rather than just a plain tuple. This should either have a value, or a string/error code. This should force the caller to handle at least one case, for example by having OnSuccess(Action<T>) and OnFail(Action<string) methods. See Result of T for an example
If this is preferable to exceptions somewhat depend on if failure is expected or not. I think it is appropriate for something like a Parse-method. For reading a file I would prefer exceptions since reading the file can fail at any time for many possible reasons. I.e. a result object fits best with a functional style.

Object reference not set to an instance of an object with no error line [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I know that it is a wrong type of question but I have been tired...
I have sent the published files to the customer and now they say they have an error. They printed the error for me. It is something like this:
It is an intranet application and does not have any problem in my local and because of security reason I can not remote to their server.
What is your suggestions...
Any help...
The exception means some object is null and you try to access one of it's properties or methods.
The exception is thrown from ReportSection method from SiteMaster class, you can put your .pdb files beside your dll to get the line number too.
If want error line to be printed in your Error stack trace than you have to include .pdb file.
Pdb file generally contains debugging information used by the debugger.
So you have to put .pdb file along with .dll file to get more debugging information.

What do the + numbers mean in a stack trace [duplicate]

This question already has answers here:
What do the "+n" values mean at the end of a method name in a stack trace?
(4 answers)
Closed 9 years ago.
I am trying to track down an exception thrown in a c# web app I have created and was wondering if someome could tell me what the + numbers relate to on each line in the stack trace
It's the offset from the start of the method, so the Exception is thrown 110 bytes (in IL) from the start of GetEmployee (which is not directly translatable to a line number due to compiling, jitting, inlining etc.)

C#: Article about throwing proper type of exception [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Sometimes I dont know witch type of exception should I throw. So I usually throw Exception(). Is there some nice article about this?
The problem with throwing a generic exception is that it restricts the ability of your code further up the stack to handle it properly (i.e. best practice is to trap the most specific exception possible before falling back, and to only capture what you can handle).
Jeffrey Richter has an excellent section on exception handling (including info on the System.Exception namespace) in CLR via C#
"Framework Design Guidelines" by Cwalina and Abrahms covers this topic really well (IMHO).
It is available for free online here, or the book (not free) here (UK) or here(US). Look in the section entitled Design Guidelines for Exceptions.
If you are not making any attempt to recover from an error, you can just throw an Exception with a string to tell you what went wrong. (Or if you will perform the same action regardless of what error occurred).
Other than making it obvious to a programmer what went wrong by using a new exception name rather than putting it in the Message, and exception can contain data to help you recover from a particular exception.
For example, an ArgumentNullException has a property ParamName, which you should set when you throw the exception. When the caller catches it, he can then look up this property and decide to pass a new value for the argument which caused the error, or can print a relevant error to inform the programmer what went wrong.
It's unfortunate that exceptions are rarely used to their full potential (in many open source APIs and such), and are often simply inserted to inform a programmer what went wrong. There's not much difference between these 2 if you don't plan to read the ParamName property when you catch it. (Many people will not bother, and only catch an Exception anyway).
throw new ArgumentNullException("arg1");
throw new Exception("arg1 is null");
It can be difficult to recover from an error fully, but in some applications though, you might find it desirable to create custom exceptions which can provide all the details you need.
For now, I would just put Exception into the Object browser search in VS, and see what is there already. Their names are pretty self explanatory, so you should be able to pick out something suitable.
Well, the one thing you shouldn't do is throw Exception itself.
Always look for an appropriate subclass.
I don't know of any publication spelling out which exception to throw when, but ArgumentException and InvalidOperationException should take care of most of your cases.
Ask separate questions about separate cases if they come up.
I would suggest dividing exceptions into a few categories based upon the system state:
The method failed in such a fashion that it did nothing; the state of any underlying data was not disturbed, and is probably valid. Typical scenarios: trying to retrieve from a collection an object which isn't there, or add one which already is. Another possible scenario: a communications timeout in cases where it should not have caused any data loss (and were retrying the operation might succeed if the problem was simply that the other end was simply too slow).
The method failed in a fashion which may have disturbed the underlying data structure, or the underlying data structure may have been corrupted previously. Further operations should not be attempted with this data structure unless steps are taken to validate it. Another possible scenario: a communications timeout occurs when a record has been partially retrieved, and the partially-retrieved data is now lost. Depending upon the protocol, it may be necessary to perform some recovery action on the connection, or to close it and initiate a new one.
Something is seriously wrong with the system state, and recovery is likely not possible.
Unfortunately, existing .net exceptions don't fit anything like that pattern; it would have been nice if there were a type ExceptionBase from which things like ThreadAbortException, CpuHasCaughtFireException, and the 'normal' Exception were derived, and all 'normal' exceptions were derived from Exception. I understand that .net 4.0 somewhat kludges in such a design, but I don't know the exact mechanics. In any case, I would suggest that any user-defined exceptions should be divided into groups as above, with all exceptions in each group sharing a common ancestor distinct from other groups.
There's an article by Krzysztof Cwalina ("a Principal Architect on the .NET Framework team at Microsoft") called Choosing the Right Type of Exception to Throw that sheds some light on this. It deals with choosing the right exception to throw and guidance on creating custom exceptions.

Handling Exceptions [closed]

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
I am working in a code-base(C# 3.5), which is littered with exception handling blocks which return true/false, when inside in a function which returns 'bool'.
catch (Exception ex) { return false; }
This is not correct practice.I am thinking of logging the exception, and have a local variable(to function) which will be initialized.And, this variable will be returned at the end of function.
What do you think?
The usual accepted way to handle exception is to handle them only if you can do something about it. You can of course handle a generic exception just for log puroposes but you should reraise it once you're done.
Your application logic shouldn't rely on exceptions. If there is absolutely no other way to do it, then at least handle concrete exceptions instead of the generic one...
Personally, I would get rid of all of these catch blocks and let the exception bubble up when it happens.
As you say, using exceptions for application logic is bad practice.
Have a catchall exception handler that will catch all such exceptions and log them and terminate the program (if that's the right thing for this program).
It is highly subjective what you want here.
It is old C-style code to have your functions return a true/false value depending on the function succeding or not. In the C# world, it is alot more common to throw exceptions.
You can debate for a long time which is the right path to choose for your code base.
My general point of view is to stick to the exceptions, they have the advantage that they bubble up and usually require less code. And there is also great support for actually logging uncaught exceptions.
You inherited code where the original programmer just didn't want to deal with errors. As written, the program will simply malfunction (say, not save a record to the database) and there's no way to find out why it malfunctioned. Especially since this is dbase code, this will cause random data corruption and loss of precious data.
You indeed cannot leave the code the way it is. The very first thing you need to do is remove all try/catch statements so the program terminates when there's an error. Add an AppDomain.UnhandledException event handler to log the exception so you know what went wrong. Fix errors you'll encounter by correcting code or validating the data. Do expect this to take time, it is very likely that you'll discover many design problems that were shoved under a doormat before.
That's certainly better than what you've got!
Although I wouldn't recommend using the bool return value as proper exception handling, if there is already a lot of code written that way, going and making sweeping modifications everywhere may not be the best idea.
Throwing an exception is generally better than returning false - an exception can at least give the receiver some clue of what happened and why the failure occurred.
The return value of a method should be the result of a method, or it should throw an exception explaining why the requested operation could not be completed.

Categories