Saturday, 22 February 2014

Exception

Exception is an event that disrupts the normal flow of execution.

When an error occurred in a method, then the method creates an exception object, and handle it to the Java Run time system. The exception object contains information about exception type, the line where the exception occurred, stack trace etc.,

Example
class ExceptionEx{
 void print(){
  System.out.println(10/0);
 }

 void callPrint(){
  print();
 }

 public static void main(String args[]){
  ExceptionEx obj = new ExceptionEx();
  obj.callPrint();
 }
}
 
When you tries to run the above program, Java Run time system throws the below error

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionEx.print(ExceptionEx.java:4)
    at ExceptionEx.callPrint(ExceptionEx.java:8)
    at ExceptionEx.main(ExceptionEx.java:13)

As you observe the above error message, below things are clear.

1. Exception Type is : ArithmeticException: / by zero

2. The method where exception occurred is ExceptionEx.print(ExceptionEx.java:4)
Above line tells that exception occured in the method print.

3. The line where exception occurred is : ExceptionEx.java:4

Where ExceptionEx.java is the file name where error occurred and line number 4, causes the error.

4. Stack trace give the detailed view to find the root cause of the exception.

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionEx.print(ExceptionEx.java:4)
    at ExceptionEx.callPrint(ExceptionEx.java:8)
    at ExceptionEx.main(ExceptionEx.java:13)

From the stack trace, we can sure that exception occurred in the method print(), which is called by callPrint(), which in turn called by the main method.

If the program don't have any exception handling mechanism, then the Java run time system throws the exception and terminates. That is what happened in the above program.

Different Garbage Collectors                                                 Handling Exceptions                                                 Home

No comments:

Post a Comment