In: Computer Science
Java try and catch problem
public void method1(){
int[] array = new int[1];
try{ array[2] = 0;}
catch(ArithmeticException e){array[2] = 0} // ?
finally{ return 0;}}
Could you please tell me why the line with the question mark will not report an error?
Detailed explanation :-
try{
//The code that might generate an exception is placed here .
// In the given code , array[2]=0 generates the exception . It is because the we try to store value 0 in a unallocated memory.
// When such exception occurs, it is caught by the catch block that immediately follows it.
}
catch{
//catch block handles such exceptions .
// Catch block is executed only when their is an exception in try block.Otherwise , catch block is skipped .
// catch block is used to handle the Exception by declaring the type of exception within the parameter.
// In the above code , ArithmeticException class is mentioned in the parameter .Hence , all the arithemtic Exceptions like array overflow are handled .Therefore , the error array[2]=0 is handled by the catch block and the code executes without any errors and the rest of program continues .
}
finally{
// finally block is always executed whether exception is found or not Java finally block follows try or catch block.
}
------------------------------------------------------------
Thank you.