[HD Pg 292, Sec. 10.4.0 - common-exceptions-that-are-usually-thrown-by-the-jvmexceptions-thrown-by-jvm]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

[HD Pg 292, Sec. 10.4.0 - common-exceptions-that-are-usually-thrown-by-the-jvmexceptions-thrown-by-jvm]

Post by OCAJO1 »

I rewrote the code in the section as nested try blocks.

Questions:

1. Is it a ok practice to, shall we say, abuse try/catch nested blocks in this fashion?
2. As in other nested blocks (i.e. if-else if), just looking at this code, I have to ask, how many levels, before is time to redesign the code?

Code: Select all

int[] ia = new int[]{ 1, 2, 3};
        
        try{
            System.out.println(ia[-1]); //ArrayIndexOutOfBoundsException
            
        }catch(ArrayIndexOutOfBoundsException ai1){
            System.out.println(ai1);
            try{
            System.out.println(ia[3]); //ArrayIndexOutOfBoundsException
            }catch(ArrayIndexOutOfBoundsException ai3){
                System.out.println(ai1);
                try{
                   System.out.println("0123".charAt(4)); //StringIndexOutOfBoundsException  
                }catch(StringIndexOutOfBoundsException si){
                    System.out.println(si);    
                } 
            }
        }  

admin
Site Admin
Posts: 10392
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 292, Sec. 10.4.0 - common-exceptions-that-are-usually-thrown-by-the-jvmexceptions-thrown-by-jvm]

Post by admin »

Design decisions are almost always subjective. If you have a valid reason (having no time think about a better design is also a reason), you can justify almost any thing that achieves the objective.

I would try to completely avoid nested try catch blocks.

Post Reply

Who is online

Users browsing this forum: Bing [Bot], vs2013 and 73 guests