Page 1 of 1

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

Posted: Fri Mar 15, 2019 6:03 pm
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);    
                } 
            }
        }  

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

Posted: Fri Mar 15, 2019 10:00 pm
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.