Understanding Exceptions

What is an Exception?

  • An exception is an event that disrupts the normal flow of the program during execution. It is an object that represents an error or unexpected event that occurs while a program is running.
  • Exception handling doesnt mean reparing an exception we have to provide alternative way to continue the rest of the program normally is the concept of Exception handling.
  • Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs.

NOTE:

  • Exception handled in try block and catched in catch block.
  • Internally Default exception handler will use the printStackTrace() method to print exception information to the console.
  • Within the try-catch block if there is no chance of rising an exception then we cant write catch block for that exception otherwise we will get compile time error.

    Example:

    public class Test1
    {
        public static void main(String[] args) throws Exception
        {
           try {
               System.out.println("Hello");
           } catch (IOException e) {
               e.printStackTrace();
           }
        }
    }
    java: exception java.io.IOException is never thrown in body of corresponding try statement
Default Exception Handling
  • Inside a method if any Excepiton occurs the method in which Exception is occured is responsible to create Exception object by including the following information.
    1. Name Of Exception.
    2. Description Of Exception.
    3. Location at which Exception occurs ( stack trace ).
  • After creating Exception object method handovers that object to the jvm.
  • JVM will check whether the method contains any Exception handling code or not. If the method doesnt contain Exception handling code then jvm terminates this method abnormally and removs corresponding entry from the stack.
  • Then jvm identifies caller method and check whether caller method contains any Exception handling code or not.
  • If the caller method doesn't contain handling code then jvm teminates that caller method also abnormally and removes the corresponding entry from the stack. This process continues until the main() method and if main() method also doesn't handle the exception then jvm terminates main() method also abnormally and removes corresponding entry from the stack.
  • Then jvm handovers responsibility of Exception handling to the Default Exception Handler which is the part of the jvm.
  • Default Exception Handler print Exception information in the following format and teminates the program abnormally.

    Exception in thread XXX: Name of the Exception: Description
    Stack Trace
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Test.doMoreStuff(Test.java:15)
	at Test.doStuff(Test.java:10)
	at Test.main(Test.java:5)