Handle or Declare The Exception Programming

Analysis on below program

  • Class CheckedExceptionWorkerDeclare is trying to access the value which is not exist in the array. So exception handler will raise a flag for ArrayIndexOutOfBoundsException
  • Throws is used to duck the exception back to calling method.
  • Exception will be raised at line System.out.println(value[9]);
  • So no further code will be executed from this class.
 
package technical.jungle.com.exception;public class CheckedExceptionWorkerDeclare {

/*
* If we receive exception “ArrayIndexOutOfBoundsException” then duck it.
* Means pass it to calling function.
*/
public void process() throws ArrayIndexOutOfBoundsException {
System.out.println(“CheckedExpetionWorker –> process() — Start”);
int value[] = { 1, 2, 3, 4 };
/*
* value[9] doesn’t exit. So it will lead to exception.
*/
System.out.println(value[9]);

System.out.println(“CheckedExpetionWorker –> process() — Ends”);
}

}

  • Now the control is passed back to method worker.process() of class CheckedExceptionDemoDeclare.
  • As this is the main class, so at this level throws exception has to be handled at any cost.
  • That is the reason try {..} catch {..} block is coded here.
 
package technical.jungle.com.exception;public class CheckedExceptionDemoDeclare {

public static void main(String arfs[]) {
System.out.println(“TechnicalJungle.com”);
CheckedExceptionWorkerDeclare worker = new CheckedExceptionWorkerDeclare();
try {
worker.process();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“CheckedExpetionDemo – catch”);
}
System.out.println(“CheckedExpetionDemo – all done”);
}
}

Output:
TechnicalJungle.com
CheckedExpetionWorker –> process() — Start
CheckedExpetionDemo – catch
CheckedExpetionDemo – all done

Conclusion


Declare means using “throws”.
Handle means try {..} catch {..}

 

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.