0

Working with some legacy code, and encountered this:

    File file = new File()
    File[] files = file.listFiles();
    for(int i=0;i<files.length;i++)
        try {
            {
                System.out.println("Do stuff");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

it compiles and runs, but I don't know which loop is inside the other, or why it works.

2 Answers2

2

This code

    File file = new File();
    File[] files = file.listFiles();
    for (int i = 0; i < files.length; i++) 
        try {
            {
                System.out.println("Do stuff");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Is same as this one

    File file = new File();
    File[] files = file.listFiles();
    for (int i = 0; i < files.length; i++) {
        try {
            {
                System.out.println("Do stuff");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

And same as this one

    File file = new File();
    File[] files = file.listFiles();
    for (int i = 0; i < files.length; i++) {
        try {
            System.out.println("Do stuff");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Java allows you to have some "extra" brackets, but it does not change anything (well it change the scope of variables if you declare them inside it, but this is not the case)

libik
  • 22,239
  • 9
  • 44
  • 87
1

try-catch isn't a loop, it's just a construct that executes the try block (once) and the possibly the catch block(s).

If you break it down, here's what's going on:

  • for each index i in the files array
    • do one thing, a try-catch
      • the try block itself has an "anonymous block" (the block created by the curlies inside the try -- it starts at the second curly brace after the word try)
        • the anonymous block has one statement, System.out.println("Do stuff");
      • the catch block prints the exception's stack trace (if an exception thrown, of course)
Community
  • 1
  • 1
yshavit
  • 42,327
  • 7
  • 87
  • 124