OCP Question 59, Explanation

Given:

class NoNameException extends Exception{}
class YearOutOfRangeException extends Exception{}
class Company{
    String name;
    int est;
    Company(String name, int est) throws Exception {
        if(name == null) {
            throw new NoNameException();
        }else if(est <= 0 || est >= 2100) {
            throw new YearOutOfRangeException();
        }else{
            this.name = name;
            this.est = est;
        }
    }
    public String toString(){
        return name + " was founded in " + est;
    }
}

And given the code fragment:

26. class Test{
27.     public static void main(String[] args) {
28.         Company comp1 = new Company("Google", 1998);
29.         Company comp2 = new Company("Microsoft", 1975);
30.         System.out.println(comp1);
31.         System.out.println(comp2);
32.     }
33. }

Which change enables the code to print the following?

Google was founded in 1998

Microsoft was founded in 1975

A. Replacing line 27 with

    public static void main (String [] args) throws NoNameException, YearOutOfRangeException {

B. Replacing line 27 with

    public static void main (String [] args) throws Exception {

C. Enclosing line 28 and line 29 within a try block and adding:

    catch (Exception e) { /* code goes here */ }
    catch (NoNameException nne) { /* code goes here */ }
    catch (YearOutOfRangeException yoore) { /* code goes here */ }

D. Enclosing line 28 and line 29 within a try block and adding:

    catch (NoNameException nne) { /* code goes here */ }
    catch (YearOutOfRangeException yoore) { /* code goes here */ }

 

The correct answer is B.

 

This Problem doesn’t test us on anything new; all what’s needed here is the CSR that we learned for our OCA exam.

First off, wrapping up the object-creating LOCS in a try block would be a syntactically unsound move as these objects cease to exist beyond the block’s boundaries, which makes options C and D irrelevant. Besides, the first catch in C is placed on the top while its proper place is at the bottom because Exception is wider than NoNameException and YearOutOfRangeException. Option D is wrong, too, because the Company’s ctor throws an Exception, which cannot be caught with the catches available in option D.

This leaves us options A and B. While the ctor in Company does throw either NoNameException or YearOutOfRangeException, its signature speaks of Exception, which is taken care of only by option B.

Leave Comment

Your email address will not be published. Required fields are marked *