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 开发者_C百科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.
精彩评论