I'm importing several fields, and that is, about 25 lines of code each importing one field (in my case, there's really no other way).
It's in a try-catch block, but there are some times, that this field doesn't exist in the source, but I have to get the rest.
from 20.
I get 10
the 11th one doesn't exist (exception)
I still need from 12 to 20.
In case I don't want to test the existence one by one, I'd like to know how try works. in case of an exception, it doesn't execute the rest, right? what could fit for me ?
obs: it's way more than 20, I want a smart-and-non-poluting solution for it.
If an exception occurs within a try block, nothing after the exception will get executed. So if the exception happens on item 11, items 12 - 20 will not get executed. The execution will jump from item 11 to the catch block and then to the finally block if there is a finally block.
From what your question has said, you get the exception when a field doesn't exist. I recommend checking to see if the field exists, and then do the operation. I do NOT recommend using a try catch as a means to check an existence condition. Try catches should be for error handling, and if you do get an error, you normally do not want to continue normal execution. If you don't like the idea of checking the condition on each line, or there is no other way to check it other than catching an exception, then I suggest making a help function with the try catch in that
boolean checkField(field){
try{/* do operation on field*/}
catch(Exception e){return false;}
return true;
}
void main(){
if !(checkField(field1)) return;
else if !(checkField(field2)) return;
.
.
.
}
Yes, an exception does break the try block - that is the way to handle them.
If you want to keep going, you need try/catch for every field. This doesn't mean writing it 20 times, far from it, refactor your code:
Add a function that gets the field (as string?) and tries to return a value.
Create a new class and define every field as an object.
Don't throw an exeption at all - if this is a common scenario, don't throw an exception! Add a check before you read the value. Again, moving this to a function will help.
Here is try-catch-finally
I would still recomend to check fro the existance of the field. This is cleaner, and more correct.
Exceptions in a loop will be a lot slower than just checking for validity.
When an exception occurs within a try block, it will jump staright out to the catch block (if there isn't a catch block, it will jump into the finally block and the exception will be bubbled up. So, the code in the try block AFTER the error occurs will not be executed.
Either:
1) Check the existence of the field before each attempt
2) wrap each individual field import in it's own try...catch
I'd go for 1), prevent exceptions happening in the first place.
If you refactor/split out code to check the existence of a field into a separate reusable method, it's not really that much effort.
Related
I'm currently getting an exception thrown and the message it gives is Value does not fall within the expected range. I'm trying to right a piece of code to grab this exception and suppress it - I know what the issue is - essentially someone is trying to pull a record from a list using an id which doesn't exist.
Any ideas how i go about catching this?
To suppress an exception you need to do something like this
try
{
// Code that may throw an exception.
}
catch (Exception ex) // Better to use a more specific exception class
{
// Do nothing - That suppresses the exception.
// If you want to do additional checking that may continue the exception
// up the stack use "throw" on its own - which compiled to CIL/MSIL's
// "rethrow" and doesn't drop much of the information that would
// go if you did "throw ex"
}
That's all there is to suppressing an exception.
For the sanity of those that have to maintain this code (or yourself in 6 months time when you've forgotten the specifics of why you did this), it would also be good to comment exactly why you are suppressing the exception. If I see code that suppresses an exception I always want to know why.
Use a try catch block with an empty catch ?
if you want to get really specific you can use an exception filter to catch only that case (in c# 6 of course).
I sometimes run into situations where I need to catch an exception if it's ever thrown but never do anything with it. In other words, an exception could occur but it doesn't matter if it does.
I recently read this article about a similar thing: http://c2.com/cgi/wiki?EmptyCatchClause
This person talks about how the comment of
// should never occur
is a code smell and should never appear in code. They then go onto explain how the comment
// don't care if it happens
is entirely different and I run into situations like this myself. For example, when sending email I do something similar to this:
var addressCollection = new MailAddressCollection();
foreach (string address in addresses)
{
try
{
addressCollection.Add(address);
}
catch (Exception)
{
// Do nothing - if an invalid email occurs continue and try to add the rest
}
}
Now, you may think that doing this is a bad idea since you would want to return to the user and explain that one or more messages could not be sent to the recipient. But what if it's just a CC address? That's less important and you may still want to send the message anyway even if one of those addresses was invalid (possibly just a typo).
So am I right to use an empty catch block or is there a better alternative that I'm not aware of?
You are completely right to use an empty catch block if you really want to do nothing when a certain type of exception occurs. You could improve your example by catching only the types of exceptions which you expect to occur, and which you know are safe to ignore. By catching Exception, you could hide bugs and make it harder for yourself to debug your program.
One thing to bear in mind regarding exception handling: there is a big difference between exceptions which are used to signal an error condition external to your program, which is expected to happen at least sometimes, and exceptions which indicate a programming error. An example of the 1st would be an exception indicating that an e-mail couldn't be delivered because the connection timed out, or a file couldn't be saved because there was no disk space. An example of the 2nd would be an exception indicating that you tried to pass the wrong type of argument to a method, or that you tried to access an array element out of bounds.
For the 2nd (programming error), it would be a big mistake to just "swallow" the exception. The best thing to do is usually to log a stack trace, and then pop up an error message telling the user that an internal error has happened, and that they should send their logs back to the developers (i.e. you). Or while developing, you might just make it print a stack trace to the console and crash the program.
For the 1st (external problem), there is no rule about what the "right" thing is to do. It all depends on the details of the application. If you want to ignore a certain condition and continue, then do so.
IN GENERAL:
It's good that you are reading technical books and articles. You can learn a lot from doing so. But please remember, as you read, you will find lots of advice from people saying that doing such-and-such a thing is always wrong or always right. Often these opinions border on religion. NEVER believe that doing things a certain way is absolutely "right" because a book or article (or an answer on SO... <cough>) told you so. There are exceptions to every rule, and the people writing those articles don't know the details of your application. You do. Make sure that what you are reading makes sense, and if it doesn't, trust yourself.
An empty catch block is fine in the right place - though from your sample I would say you should cetagorically NOT be using catch (Exception). You should instead catch the explicit exception that you expect to occur.
The reason for this is that, if you swallow everything, you will swallow critical defects that you weren't expecting, too. There's a world of difference between "I can't send to this email address" and "your computer is out of disk space." You don't want to keep trying to send the next 10000 emails if you're out of disk space!
The difference between "should not happen" and "don't care if it happens" is that, if it "should not happen" then, when it does happen, you don't want to swallow it silently! If it's a condition you never expected to occur, you would typically want your application to crash (or at least terminate cleanly and log profusely what's happened) so that you can identify this impossible condition.
If an exception should never be thrown then there is no point catching it - it should never happens and if it does you need to know about it.
If there are specific scenarios that can cause a failure that you are OK with then you should catch and test for those specific scenarios and rethrow in all other cases, for example
foreach (string address in addresses)
{
try
{
addressCollection.Add(address);
}
catch (EmailNotSentException ex)
{
if (IsCausedByMissingCcAddress(ex))
{
// Handle this case here e.g. display a warning or just nothing
}
else
{
throw;
}
}
}
Note that the above code catches specific (if fictional) exceptions rather than catching Exception. I can think of very few cases where it is legitimate to catch Exception as opposed to catching some specific exception type that you are expecting to be thrown.
Many of the other answers give good reasons when it would be ok to catch the exception, however many classes support ways of not throwing the Exception at all.
Often these methods will have the prefix Try in front of them. Instead of throwing a exception the function returns a Boolean indicating if the task succeeded.
A good example of this is Parse vs TryParse
string s = "Potato";
int i;
if(int.TryParse(s, out i))
{
//This code is only executed if "s" was parsed succesfully.
aCollectionOfInts.Add(i);
}
If you try the above function in a loop and compare it with its Parse + Catch equilvilant the TryParse method will be much faster.
Using an empty catch block just swallows the Exception, I would always handle it, even if it is reporting back to you that an Exception occurred.
Also catching the generic Exception is bad practice due to the fact it can hide bugs in your application. For example, you may have caught an ArgumentOutOfRange exception which you did not realize was happening and then swallowed it (I.e. not done anything with it).
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.
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.
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.