java - which one have more priority ArithmeticException and ArrayIndexOutOfBoundsException -


i wrote program little confusing on know throw arithmeticexception before through arrayindexoutofboundsexception expected throwing arithmeticexception.

i have below code :

try{             int arrray[]={1,3};             arrray[2]=3/0+arrray[5];         }catch(arrayindexoutofboundsexception ie){             ie.printstacktrace();         }         catch(arithmeticexception ie){             ie.printstacktrace();         }         catch(exception e){             e.printstacktrace();         } 

thanks help

it's pretty easy test , find out:

$ cat demo1.java  class demo1 {   public static void main(string[] args) {     try {       int[] array = {};       int impossible = 1/0 + array[0];     } catch (exception e) {       system.out.println("caught " + e.getclass().getsimplename());     }   } }  $ cat demo2.java  class demo2 {   public static void main(string[] args) {     try {       int[] array = {};       int impossible = array[0] + 1/0;     } catch (exception e) {       system.out.println("caught " + e.getclass().getsimplename());     }   } }  $ cat demo3.java  class demo3 {   public static void main(string[] args) {     try {       int[] array = {};       array[0] = 1/0 + array[0]; // assignment happens last     } catch (exception e) {       system.out.println("caught " + e.getclass().getsimplename());     }   } }  $ javac demo*.java  $ java demo1 caught arithmeticexception  $ java demo2 caught arrayindexoutofboundsexception  $ java demo3 caught arithmeticexception 

as can see neither has priority, instead it's order dependent. subcomponents of expression evaluated in-order left right, therefore if left-hand operand raises exception right hand side never evaluated.

since exception occurs during expression evaluation assignment array[2] never occurs, because assignment can't happen until expression on right-hand-side has been executed value can assigned.

this answer goes more detail relevant java language specifications define behavior.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -