I have a loop that looks something like this:
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this:
try {
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
} catch (NumberFormatException ex) {
return null;
}
But then I also thought of putting the try...catch block inside the loop, like this:
for (int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
} catch (NumberFormatException ex) {
return null;
}
myFloats[i] = myNum;
}
Is there any reason, performance or otherwise, to prefer one over the other?
Edit: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?
PERFORMANCE:
There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.
Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html
The table is described about half-way down.
Performance: as Jeffrey said in his reply, in Java it doesn't make much difference.
Generally, for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not.
In your example you returned upon catching an exception. In that case, I'd put the try/catch around the loop. If you simply want to catch a bad value but carry on processing, put it inside.
The third way: You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop. Making the exception handling isolated to the loop itself!
class Parsing
{
public static Float MyParseFloat(string inputValue)
{
try
{
return Float.parseFloat(inputValue);
}
catch ( NumberFormatException e )
{
return null;
}
}
// .... your code
for(int i = 0; i < max; i++)
{
String myString = ...;
Float myNum = Parsing.MyParseFloat(myString);
if ( myNum == null ) return;
myFloats[i] = (float) myNum;
}
}
All right, after Jeffrey L Whitledge said that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
public class Main {
private static final int NUM_TESTS = 100;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, Jeffrey is correct; there is absolutely no performance difference on Java 6, Sun client VM (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or Ray Hayes's way.
While performance might be the same and what "looks" better is very subjective, there is still a pretty big difference in functionality. Take the following example:
Integer j = 0;
try {
while (true) {
++j;
if (j == 20) { throw new Exception(); }
if (j%4 == 0) { System.out.println(j); }
if (j == 40) { break; }
}
} catch (Exception e) {
System.out.println("in catch block");
}
The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.
Before any details, here the other example:
Integer i = 0;
while (true) {
try {
++i;
if (i == 20) { throw new Exception(); }
if (i%4 == 0) { System.out.println(i); }
if (i == 40) { break; }
} catch (Exception e) { System.out.println("in catch block"); }
}
Same logic as above, only difference is that the try/catch block is now inside the while loop.
Here comes the output (while in try/catch):
4
8
12
16
in catch block
And the other output (try/catch in while):
4
8
12
16
in catch block
24
28
32
36
40
There you have quite a significant difference:
while in try/catch breaks out of the loop
try/catch in while keeps the loop active
I agree with all the performance and readability posts. However, there are cases where it really does matter. A couple other people mentioned this, but it might be easier to see with examples.
Consider this slightly modified example:
public static void main(String[] args) {
String[] myNumberStrings = new String[] {"1.2345", "asdf", "2.3456"};
ArrayList asNumbers = parseAll(myNumberStrings);
}
public static ArrayList parseAll(String[] numberStrings){
ArrayList myFloats = new ArrayList();
for(int i = 0; i < numberStrings.length; i++){
myFloats.add(new Float(numberStrings[i]));
}
return myFloats;
}
If you want the parseAll() method to return null if there are any errors (like the original example), you'd put the try/catch on the outside like this:
public static ArrayList parseAll1(String[] numberStrings){
ArrayList myFloats = new ArrayList();
try{
for(int i = 0; i < numberStrings.length; i++){
myFloats.add(new Float(numberStrings[i]));
}
} catch (NumberFormatException nfe){
//fail on any error
return null;
}
return myFloats;
}
In reality, you should probably return an error here instead of null, and generally I don't like having multiple returns, but you get the idea.
On the other hand, if you want it to just ignore the problems, and parse whatever Strings it can, you'd put the try/catch on the inside of the loop like this:
public static ArrayList parseAll2(String[] numberStrings){
ArrayList myFloats = new ArrayList();
for(int i = 0; i < numberStrings.length; i++){
try{
myFloats.add(new Float(numberStrings[i]));
} catch (NumberFormatException nfe){
//don't add just this one
}
}
return myFloats;
}
As already mentioned, the performance is the same. However, user experience isn't necessarily identical. In the first case, you'll fail fast (i.e. after the first error), however if you put the try/catch block inside the loop, you can capture all the errors that would be created for a given call to the method. When parsing an array of values from strings where you expect some formatting errors, there are definitely cases where you'd like to be able to present all the errors to the user so that they don't need to try and fix them one by one.
If its an all-or-nothing fail, then the first format makes sense. If you want to be able to process/return all the non-failing elements, you need to use the second form. Those would be my basic criteria for choosing between the methods. Personally, if it is all-or-nothing, I wouldn't use the second form.
As long as you are aware of what you need to accomplish in the loop you could put the try catch outside the loop. But it is important to understand that the loop will then end as soon as the exception occurs and that may not always be what you want. This is actually a very common error in Java based software. People need to process a number of items, such as emptying a queue, and falsely rely on an outer try/catch statement handling all possible exceptions. They could also be handling only a specific exception inside the loop and not expect any other exception to occur.
Then if an exception occurs that is not handled inside the loop then the loop will be "preemted", it ends possibly prematurely and the outer catch statement handles the exception.
If the loop had as its role in life to empty a queue then that loop very likely could end before that queue was really emptied. Very common fault.
My perspective would be try/catch blocks are necessary to insure proper exception handling, but creating such blocks has performance implications. Since, Loops contain intensive repetitive computations, it is not recommended to put try/catch blocks inside loops. Additionally, it seems where this condition occurs, it is often "Exception" or "RuntimeException" which is caught. RuntimeException being caught in code should be avoided. Again, if if you work in a big company it's essential to log that exception properly, or stop runtime exception to happen. Whole point of this description is PLEASE AVOID USING TRY-CATCH BLOCKS IN LOOPS
In your examples there is no functional difference. I find your first example more readable.
You should prefer the outer version over the inner version. This is just a specific version of the rule, move anything outside the loop that you can move outside the loop. Depending on the IL compiler and JIT compiler your two versions may or may not end up with different performance characteristics.
On another note you should probably look at float.TryParse or Convert.ToFloat.
If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.
I's like to add my own 0.02c about two competing considerations when looking at the general problem of where to position exception handling:
The "wider" the responsibility of the try-catch block (i.e. outside the loop in your case) means that when changing the code at some later point, you may mistakenly add a line which is handled by your existing catch block; possibly unintentionally. In your case, this is less likely because you are explicitly catching a NumberFormatException
The "narrower" the responsibility of the try-catch block, the more difficult refactoring becomes. Particularly when (as in your case) you are executing a "non-local" instruction from within the catch block (the return null statement).
If you want to catch Exception for each iteration, or check at what iteration Exception is thrown and catch every Exceptions in an iteration, place try...catch inside the loop. This will not break the loop if Exception occurs and you can catch every Exception in each iteration throughout the loop.
If you want to break the loop and examine the Exception whenever thrown, use try...catch out of the loop. This will break the loop and execute statements after catch (if any).
It all depends on your need. I prefer using try...catch inside the loop while deploying as, if Exception occurs, the results aren't ambiguous and loop will not break and execute completely.
setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.
depending on the number of iterations, performance difference will likely be negligible.
However i agree with the others that having it outside the loop make the loop body look cleaner.
If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.
If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.
Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.
The whole point of exceptions is to encourage the first style: letting the error handling be consolidated and handled once, not immediately at every possible error site.
put it inside. You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw. Think about what would be interesting to you in the debugger at this point in the program.
Consider:
try {
// parse
} catch (NumberFormatException nfe){
throw new RuntimeException("Could not parse as a Float: [" + myString +
"] found at index: " + i, nfe);
}
In the time of need you will really appreciate an exception like this with as much information in it as possible.
That depends on the failure handling. If you just want to skip the error elements, try inside:
for(int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
} catch (NumberFormatException ex) {
--i;
}
}
In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.
I'll put my $0.02 in. Sometimes you wind up needing to add a "finally" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:
try {
for(int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
}
} catch (NumberFormatException ex) {
return null;
} finally {
dbConnection.release(); // Always release DB connection, even if transaction fails.
}
Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.
Another aspect not mentioned in the above is the fact that every try-catch has some impact on the stack, which can have implications for recursive methods.
If method "outer()" calls method "inner()" (which may call itself recursively), try to locate the try-catch in method "outer()" if possible. A simple "stack crash" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.
In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.
Related
I am doing some practice problems and the current problem I am working on involves me constantly checking surrounding values in a 2D array.
I am wondering what is the best way to go about handling out of bounds exceptions for a problem like this. Should I be using try-catch blocks for each index I am checking? The catch part would not be utilized in this case since I wouldn't want to print anything or end the program if an error occurs. This is why I think there may be a better way to handle this.
This is some simplified code for the "index checking"
private static void findRoute(String[][] area, int currentRow, int currentCol) {
int row = currentRow;
int col = currentCol;
while (!area[row][col].equals("D")) {
try {
checkRight(area, row, col);
} catch (IndexOutOfBoundsException io) {
//Move on
}
try {
checkLeft(area, row, col);
} catch (IndexOutOfBoundsException io) {
//Move on
}
}
}
So, for example, if the first try-catch block results in an error, I would want it to move onto the next try-catch to check the next value.
However, if there is no error, I want to check the value at the index I was using the try-catch block on. But if I put a statement after the try-catch to get the value of checkRight(), and the error in the try-catch was thrown, then it would just give me an error and the program would crash.
Should I be handling this in a different way? Is there an easier way to handle this with if-statements or something?
In general, an exception is something which does not adhere to a rule. You expect some things and they should mostly fulfill the expectations you have, but in some exceptional cases your expectations are not met. If you ponder about this, you will realize that since softwares can have different levels, what is an exception on a lower level is not necessarily an exception in higher level and vice-versa.
The main mistake you make in organizing your code is that your concern of index bounds is handled on the level of findRoute and not on its proper level, that is, in your checkLeft and checkRight methods. On the level of findRoute, you kind of expect to have some edge cases (literally), yet, on the level of checkLeft and checkRight you need to handle this. As a result, you should move all your concern about bounds into checkLeft and checkRight. If you see value in handling out of bounds as an exception for logging or any other purpose, then you can have a try-catch on the level of these methods, but you should ensure that they handle it. For example you can modify these methods to be boolean and return true at the end of the try and false at the end of the catch, like
try {
//Do some stuff
return true;
} catch (Exception e) {
//Do some stuff
return false;
}
and then you can do something like this:
checkRight(area, row, col) || checkLeft(area, row, col);
Don't worry: if checkRight is true, checkLeft will not be called.
You can use if statement instead of try-catch construct because it is less expensive:
private static void findRoute(String[][] area, int row, int col) {
// index checking
if (row < area.length && col < area[row].length) {
// do some stuff
} else {
// do another stuff
}
}
This question is very specific to me, so I cannot find related questions on Stack Overflow. So, I'm coding a grep shown below. I am confused on the stringindextoutofboundexception. The reason for that is because I am checking whether it is equals to \0. That means I am handling the out of bound exception, no?
Example:
grep("hello","llo");
This will return 3. That is because its start matching at original[2] which is position 3. However, I am encountering an out of index error. I've spent hours and I can't figure it out.
public static int grep(String ori, String ma){
int toReturn = 0;
int oCounter = 0;
int i = 0;
while (i < ma.length()){
if (ori.charAt(toReturn) == ma.charAt(i)){
i++;
if (ma.charAt(i) == '\0'){ // error on this line
return toReturn;
}
toReturn++;
if (ori.charAt(toReturn) == '\0'){ // and this line if i delete the section above.
return -1;
}
} else {
i = 0;
toReturn++;
}
}
return -1;
}
You're getting an StringIndexOutOfBoundsException because you increment i inside the loop at a too early and wrong stage.
Checking for \0 is a C++ thing. Strings in java are not \0 terminated.
What you're writing is already done in the String class. There are several methods available.
System.out.println("hello".indexOf("llo"));
will print 2 because it's been found and starts at index 2. Feel free to add 1 if you dislike the starting at 0 for some reason.
You also ask "that means I'm handling the exception, no?". No, it doesn't. Exceptions are handled with a special syntax called try-catch statements. And example:
try {
// possibly more lines of code here
do_something_that_might_cause_exception();
// possibly more lines of code here
} catch (Exception e) {
// something did indeed cause an exception, and the variable e holds information about. We can do "exceptional" handling here, but for now we print some information.
e.printStackTrace();
}
Today I realized something that appeared weird to me: I noticed that when I just do
try {
doSomething();
} catch (Exception e) {
}
it isn't slower at all than if I just do
doSomething();
So I ran a test and wrote down some quick code to prove what I saw, the code basically just loops over a function called doSomething() lots of times, one time without and one time with try-catch surrounding it. So here's the code to it if you want to test it yourself:
public class Main {
private static final long LOOPS = 1000000L;
public static final void main(String[] args)
{
System.out.println("Loop without try catch: "+loopWithoutTryCatch(LOOPS));
System.out.println("Loop with try catch: "+loopWithTryCatch(LOOPS));
}
public static long loopWithoutTryCatch(long loops)
{
long startTime = System.currentTimeMillis();
for (long i = 0L; i < loops; i++)
{
doSomething();
}
return System.currentTimeMillis()-startTime;
}
public static long loopWithTryCatch(long loops)
{
long startTime = System.currentTimeMillis();
for (long i = 0L; i < loops; i++)
{
try {
doSomething();
} catch (Exception e) {
}
}
return System.currentTimeMillis()-startTime;
}
public static void doSomething()
{
for (int i = 0; i < 250; i++)
{
if (i % 3 == 0)
{
i++;
}
}
}
}
And I received the following output:
Loop without try catch: 375
Loop with try catch: 373
I was surprised so I tested it again and again, but I always got similar results, both ways it runs pretty much in the same time.
And now my question is: Why?
I dont really understand it, as far as I know try-catch writes the resources before usage in some kind of table to later - if any exception is thrown - be able to clean it up and reference to the values it had before the exception occured.
This should take at least some time, shouldn't it?
I thought it is maybe because I the random example I choose doesnt represent it properly, and in that specific case in which I tested it it doesnt slow down anything, but that seemed very unlikely to me.
Then I thought maybe it just takes such a tiny amount of time that it isnt noticable with that "few" amount of executions, so I ran the test program again with a total number of 10 million loopings, but what I found just prooved what I had already found: It takes pretty much the same time for both executions.
So is there any logical explanation for that this is the case or just a example-specific behaviour of try-catch?
Thanks for any clarification in advance.
The "slowness" in throw / catch blocks comes from the process of throwing and catching the exception, not in the process of setting up "traps" for them. When you throw an exception, JVM must
Create an instance of an exception
Prepare space for the stack trace
Populate the stack trace into the prepared space
"Unwind" the stack down to the correct place
Pass the control to your exception handler.
When none of that is happening, JVM simply sticks a note that an exception handler is available at this level on the stack, and continues executing the actual code.
Making the feature penalty-free was a very important goal for language designers: programmers should not be required to pay for things that they do not use. Otherwise, programmers would be tempted to skip exception handling or go back to the C ways of using status codes in order to save a few CPU cycles here and there, spelling the end to the exceptions as a feature.
The bytecode generated from code like yours follows this pattern
1: invoke method
2: goto 4
3: store exception in catch block variable
// would contain handling code if there was any
4: return // or whatever comes after the try-catch
Exception table
if an exception of the type in catch block happens from 1 to 3, goto 3
So basically all you have added with a try-catch is an extra goto if no exceptions occur. Otherwise, the JVM will lookup the exception in the exception table and match where it occurred. It will then prepare the Exception and goto whatever instruction index is specified. That whole operation is heavy.
I have a situation that the same exception is thrown too often and floods the log/console.
the code logic is like:
public void run(){
....
try {
} catch (Throwable trace) {
LOG.error("catch throwable" , trace);
}
}
Is there a way that I can change the 'catch' block, so that it only logs the nth time?
catch (Throwable trace) {
if ( the 100th time)
LOG.error("catch throwable" , trace);
else
LOG.error("catch throwable");
}
Note:
Exceptions are very expensive.
You should not use them for control flow but instead should add checks (using if statements such as: if(AAA==null) ) to avoid the exceptions in the first place.
Code:
The below would take care of it. You have a counter incrementing every time there is an exception. You take this modulo N, and when the result is zero, you log the error.
private int exceptionCounter = 1;
private static int N = 100;
public void run(){
....
try {
} catch (Throwable trace) {
if(exceptionCounter++ % N == 0)
LOG.error("catch throwable:" + String.valueOf(exceptionCounter ) + " Exceptions thrown." , trace);
}
}
Update
If your after a shared multi-threaded ExceptionCounter you need to use an atomic variable.
private static AtomicInteger exceptionCounter = new AtomicInteger();
private static int N = 100;
public void run(){
....
try {
} catch (Throwable trace) {
if(exceptionCounter.incrementAndGet() % N == 0)
LOG.error("catch throwable:" + String.valueOf(exceptionCounter ) + " Exceptions thrown." , trace);
}
}
If you think you might need this feature lots, then most logging frameworks offer a way to intercept log attempts. By extending the framework, you can decide whether or not to log something. You might even get all fancy and delay all logging by a short period, and if in that period, the same log is repeated, just merge it with the previous, along with a counter.
The first example of this that I found while google was this email throttler for log4j which uses TriggeringEventEvaluator. Are you using log4j?
Yes. You could limit the number of times the exception is thrown by declaring a global variable that is incremented in the "catch" block, and a conditional that would terminate the program if the variable's value is sufficiently large.
You can have a static volatile variable (which are accessible across threads) counting the number of times the catch block has been entered and then use the % operator to determine if it is a multiple of e.g. 10.
I would, however, suggest that you look into logging to files instead. A good log file is invaluable when needing to solve a problem in a program after it has finished.
is there any other way to break this loop without using the actual break statement?
the thing is for some reason my professor doesn't like that we use break in any other place that in the switch
i am having troubles in my method adding an object into the array of objects in the next empty space in the array
this is my code: (any other way to do it?)
public void add(Employee employeeObj)throws ArrayIndexOutOfBoundsException{
try{
for(int i= 0; i<MAX; i++){
if(listEmployee[i] == null){
listEmployee[i] = employeeObj;
break;
}
}
}catch(ArrayIndexOutOfBoundsException e){
throw new ArrayIndexOutOfBoundsException("ERROR!");
}
}
the method just need to add the employeObj into the array and if the case, thows an exception.
thanks for your help
try this:
for(int i= 0; i<MAX; i++){
if(listEmployee[i] == null){
listEmployee[i] = employeeObj;
i=MAX;
}
but I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.
You can simply do i = MAX or use a boolean flag if you don't have such a trivial situation.
As a personal note forbidding the usage of break outside switch statements doesn't make any sense.
Since your method is doing nothing else in this case, you can just use return instead of break:
public void add(Employee employeeObj)throws ArrayIndexOutOfBoundsException {
try{
for (int i= 0; i<MAX; i++) {
if (listEmployee[i] == null) {
listEmployee[i] = employeeObj;
return;
}
}
} catch(ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("ERROR!");
}
}
But in general the other answers here are more applicable. That said, I would ask your professor to explain why break shouldn't be used - IMHO alternatives are often much less readable.
i am having troubles in my method adding an object into the array of objects in the next empty space in the array
I would suggest simply finding out the length of the array and inserting the object in the next location. No need to iterate the complete length of arrray.
public void add(Employee employeeObj){
int n = listEmployee.length;
listEmployee[n] = employeeObj;
}
}
Alternatively you could do it as
int i = Arrays.asList(listEmployee).indexOf(null);
if (i >= 0) {
listEmployee[i] = employeeObj;
}
note that Arrays.asList creates a view over array, not a new List