If I have a exception code like
catch
{
throw;
}
Does it make any sense? If suppose I dont write this code in function will the exceptions be treated similar in function or there is any difference?
The code itself does nothing, but that doesn't mean it's worthless. Think of it as a stub.
I have let code like this go into production, and every time what it means is that I had trouble there at some point, and during development I had additional code that I used for debugging that was later removed... something like an extra log message, MessageBox, or trace call, or even just a no-op kind of line (string s = "";) where I could put a break point. If you go look back in source control you'll be able to see those statements.
I like to leave the stub behind as a reminder that this section might be more difficult than it appears.
Looking at any random bit of code, though, a lot of the time this code exists because someone who didn't know any better just thought there should be a try/catch block there.
No, doesn't make sense as it is not handling the exception, but is just re-throwing
No. It really doesn't make any sense by itself.
Without adding some sort of logging or other logic, this would be equivalent to not using a try/catch block at all.
This is redundant. It will catch any exception and then just rethrow it. You're better off not using the catch at all, the results are the same and the code is less cluttered.
in that situation the throw is in fact a re-throw and completely pointless if you have no other error handling.
Related
I wanted to throw an exception if something went wrong in the method resubmit()
var manager = new ApprovalsDashboardManager();
try
{
manager.Resubmit(requestId, userId);
}
catch (Exception e)
{
throw new ApplicationException("Resubmit Request Failed, Please resubmit in a while", e.InnerException);
}
Is his correct way of using try catch block and I wanted to know how to error handle methods which are in other project being called in my current project.
Syntactically, yes, this is the correct way to use a try-catch block. However, if you have access to the code, I would suggest modifying the ApprovalsDashboardManager.Resubmit() method so that it throws your custom ApplicationException when something goes wrong. It's a little redundant to catch an exception just to throw another exception.
EDIT: However, it is not "bad practice" to do this. This use-case is included in the MSDN page for try-catch. https://msdn.microsoft.com/en-us/library/0yd65esw.aspx
If your "ReSubmit" function is throwing the exception, you don't need to throw it again. It is acceptable to handle the exception simply by providing some information to the user about what happened.
So you would do this somewhere in the catch. You did right by adding some more information into the exception's Message, this is good practice.
The problem with wrapping exceptions, as you have done, is that it tends to conceal the true source of the error, because the stack trace reflects the point where the exception was thrown. This is mitigated somewhat because you've included the original exception as the InnerException.
This CAN be a legitimate thing to do, if you are hiding implementation details and don't want to expose those details to users via an exception. The user of an exception though, most often, is a developer and the more accurate and detailed information you can give them the better.
I'm also wary of catching all exceptions. What happens if you get an OutOfMemoryException, for example? Do you really want to ignore that? If you don't know what to do about running out of memory, then it might be better to let that exception bubble up to the next level where some other code might know what to do about it.
Sometimes i meet the following construction exploring ServiceStack's code base:
try
{
...
}
catch (Exception)
{
throw;
}
In my oppinion this construction does nothing. What is the possible reason of doing this?
You're right - it's generally pointless. I have seen people include it so that they can put a break point on the throw line (so they get to see when an exception is thrown, even if they're not breaking on exceptions in general). Unfortunately it often gets left in there after the debugging session has finished.
If you encounter this within a code base you control, I suggest you remove it.
Last time I stumbled over such a construct I asked the author why. Why I was particulary curious was that he did not do this all willy nilly but only in a few places.
His response came with the 'let exceptions be exceptional' which I guess he must have picked up from Eric Lippert where he added that most of his methods would/(should) never throw where in some places his code could throw. By adding the try/catch/throw he was communicating to maintainers that he had recognized that this could happen.
Naturally we try to write code that does not blow up at all. For example by using Code Contracts the number of methods that actually can throw is reduced dramatically.
I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form.
Just let the exception propagate up - you should only catch the exception if you can actually handle it. Exceptions are the "abort mechanism" in .NET. You're currently swallowing the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.
I was really hoping for some sort of like "abort mechanism" that I
could use. Is there any other ways of working around this? Any
interesting work-arounds for this?
Yes, there is. It is called exception handling.
Let's rewrite your code:
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a FormatException
You are subverting the existing "abort" mechanism by catching an exception that you are not doing anything about and swallowing it.
You should not use a try{}catch{} block in this case and let the exception bubble up and cause the application to abort.
The easiest work-around is don't catch the exception. If that were to happen, it'd go straight past the DoFurtherAnalysis() function and out to the original caller.
Don't see anything anoying in returning and checking bool return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort everything, just do not catch exception it will abort your program.
use a try...catch in the constructor?
Well, you've got several issues mixed up here. First, it looks like you do possibly-very expensive processing from your constructor. If that processing can throw, you really don't want to call it from your constructor becuase you don't even have the option of returning an error code.
Second, (and you'll read in many threads here,) how you handlee errors really depends on the application and expectation of your users. Some errors could be corrected by changes to inputs. Others might happen in the middle of the night if analysis takes a long time and you might want to continue with another analysis, logging this error.
So I think we're really going to punt back to you for more information about the above.
You could just move DoFurtherAnalysis(); into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties.
I'll try and ask my question so it doesn't end as a simple argumentative thread.
I've jumped into an application coded in C# recently and I'm discovering the exception mechanism. And I've had a few bad experiences with them such as the following
// _sValue is a string
try
{
return float.Parse(_sValue);
}
catch
{
return 0;
}
I changed it into :
float l_fParsedValue = 0.0f;
if (float.TryParse(_sValue, out l_fParsedValue))
{
return l_fParsedValue;
}
else
{
return 0;
}
Result, my Output in Visual Studio is not anymore flooded with message like
First chance System.FormatException blabla
when string like '-' arrive in the snippet. I think it's cleaner to use the second snippet.
Going a step further, I've often seen that exceptions are too often used ilke: "I do whatever I want in this try-catch, if anything goes wrong, catch.".
Now in order to not get stuck with bad misconceptions, I would like you guys to help me clearly define how/when to use those exceptions and when to stick with old school "if...else".
Thanks in advance for your help!
You should throw exception in exceptional cases. i.e. when something unexpected happens. If you expect a function to regularly throw an exception that's most likely bad design.
In your examples it is very clear that TryParse is better since the exception seems to occor often.
But for example when parsing a file, I expect it to be almost always valid. So I usually use Parse and catch the exception and generate a InvalidDataException with the caught exception as inner exception. Usually simplifies the parsing code a lot, even if it may be bad style.
I recommend Eric Lippers's blog entry: Vexing exceptions
In case of Parse()/TryParse() it's better don't wait for exception, use TryParse and act on incorrect input by yourself.
Exceptions should be used for exceptional behavior, not for flow-control. A basic guideline would be that if normal program flow regularly runs into exceptions you're doing something wrong.
However, it is important to notice that just having a try { } catch { } present will itself not affect performance negatively. Only when an exception is actually thrown and the stack trace needs to be computed you will see (in some cases quite severe) performance degradation.
Another point that hasn't been examined in depth so far is that Exceptions have a cost. They subvert the normal flow of control in the program and there is some resource use as a result.
A simple test would be to write a program that loops over your original float.Parse code with some invalid data, and compare how long it takes to run versus the TryParse version - there will be a small but noticeable difference.
A snippet that sticks in my mind when making decisions about exceptions is from this article:
Almost Rule #1
When deciding if you should throw an
exception, pretend that the throw
statement makes the computer beep 3
times, and sleep for 2 seconds. If
you still want to throw under those
circumstances, go for it.
Programs that use exceptions as part
of their normal processing suffer from
all the readability and
maintainability problems of classic
spaghetti code.
— Andy Hunt and Dave Thomas
I think there is no simple right answer about how/when to use exceptions. It depends on an architecture of the application you're working on and other factors.
I can suggest you to read the chapters 8.3. Error-Handling Techniques and 8.4. Exceptions of the Code Complete book.
Ahh, if only it was that simple! But, alas - the decision when to use exceptions is more often subjective than not. Still, there are guidelines you can use. For example, Microsoft has some.
All in all, the rule of thumb for throwing exceptions is - you only throw an exception when a function cannot do what it was supposed to do. Basically each function has a contract - it has a legal range of input values and a legal range of output values. When the input values are invalid, or it cannot provide the expected output values, you should throw an exception.
Note that there is a slippery point here - should validation (of user input) errors also be thrown as exceptions? Some schools of thought say no (Microsoft included), some say yes. Your call. Each approach has its benefits and drawbacks, and it's up to you to decide how you will structure your code.
A rule of thumb for catching exceptions is - you should only catch exceptions that you can handle. Now, this is also slippery. Is displaying the error message to the user also "handling" it? But what if it's the infamous StackOverflowException or OutOfMemoryException? You can hardly display anything then. And those might not be the only exceptions that can leave the whole system in an unusable state. So again - your call.
In a method, I want to be able to insert a value into a div which is part of the html document I choose to parse.
public void AddToDiv(string div)
{
//Code to read the html document and look for the div
//(name specified as the parameter of this method).
}
Question is, I could specify a div called "abc" but the html document may not have this div. Fair enough, but what is the difference between me saying:
try
{
//Method logic to parse document for the div
}
catch(ArgumentException ex)
{
// (I wouldn't supress this catch block in production code,
// just omitting body details for simplicity.
}
OR
public void ParseDocument
{
//Logic here...
if(!document.Contains(div)
{
throw new ArgumentException();
}
}
In short, what is the difference between a catch block and saying throw new [ExceptionType here] in the main logic block? How do I decide which is to use?
Thanks
Personally, I'd check for existence, rather than allowing the exception to be thrown, it's easier to determine the flow of logic, and fits better with the intent of your code.
See these questions and answers for a broader discussion
When to throw an exception
Is there any valid reason to ever ignore a caught exception
How slow are .net exceptions?
EDIT:
On second thoughts, you should consider the expense of the "containts" check. If it's likely to be as expensive as actually getting the div, and it's doubling the time it takes the routine to run and if this lag degrades performance to the point where it'll be noticed, then possibly it's better to just go and get the div. I'd still catch it and throw the ArgumentException, with the original exception as the inner exception.
NB: Don't optimise unless you need to.
There is a third option, but I'll write more about it later.
First of all, catching exception is all about catching errors you don't expect, handling them and either continue or close down gracefully.
Throwing exceptions should be used when you encounter situation which shouldn't occur or should be handled elsewhere. If you want to handle this error outside your method, this might be your solution.
The third alternative is to actually avoid errors you know may occur. You could for example check if the div exists and not do anything if it doesn't, also known as defensive programming.
throwing and catching are two opposite sides of exception handling. The component that encounters a disaster and can't recover from it throws the Exception. Somewhere lower down on the stack, a calling component can catch the Exception and handle it.
The difference is in this case, the pattern would be AddToDiv would throw an Exception and ParseDocument, which calls AddToDiv, could catch it and handle it.
well the Try/Catch is more expensive, and it should be used to handle unexpected errors. In this case you know you will possibly get an error and dont have to "try"
The question is: If ParseDocument(...) cannot do what you want it do do, should it fail silently? If so, use a try{} catch{} inside it. If you need the calling code to know that ParseDocument failed, it should throw an exception that this calling code can catch.