Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

predict output practice problem

Note : Execution commandline : $ java exception_handling one

class exception_handling {

    public static void main(String args[]) {

        try {

            int a = args.length;

            int b = 10 / a;

            System.out.print(a);

            try {

                if (a == 1)

                    a = a / a - a;

                if (a == 2) {

                    int c = {1};

                    c[8] = 9;

                }
            }

            catch (ArrayIndexOutOfBoundException e) {

                System.out.println("TypeA");
            }

            catch (ArithmeticException e) {

                System.out.println("TypeB");

            }
        }
    }
}

a) TypeA b) TypeB c) 0TypeA d) 0TypeB

Answer: c Explanation: Execution command line is “$ java exception_handling one” hence there is only single string that is in args array, making its length 1, hence “a = a/ a – a” in second try block is executing which throws arithmeticexception which is caught by catch of firts try block as the nested try block does not have a catch block which can detect ArithmeticException. Hence 0TypeA is printed Output: $ javac exception_handling.java $ java exception_handling 0TypeA

I dont get this, if it is passing one to the program, a would be 1, System.out.print(a) will print 1, why it is 0 ?

1 Answer

You're all wrong. :-P True output (I renamed the class to Test1):

treehouse:~/workspace$ javac Test1.java                                                                      
Test1.java:5: error: 'try' without 'catch', 'finally' or resource declarations                               
            try {                                                                                            
            ^                                                                                                
1 error                                                                                                      
treehouse:~/workspace$ 

Seriously, even if you fix the compiler errors the output would be E) 1. There's no ArithmeticException to throw because a = a / a - a evaluates as a = (a/a) - a or a = 1-a