Question

While going through Exception handling exercise in JAVA, I am bit confused about various things. Basically what I don't understand is how the flow of the program is when an exception is encountered. I would like to understand how actually the flow of the program takes place in following scenario and whether my understanding of the concepts is right or wrong.

 public void myFunction(){

     try{

            //Some code......

        }catch(Exception e1){

            //If this Exception is occured handle it here.

        }catch(Exception e2){

           //if this exception has occured then

          throw new myException("whatever message required");
        }

       finally{

           //code that has to be executed 
       }

 }

Now what my understanding is:

1.If no exception is occurs then the code runs smoothly and eventually the code in the finally block gets executed 2.If exception e1 occurs then it is caught in first catch block , it is handled there appropriately and then finally block gets executed. 3.But what happens if exception e2 occurs. In that catch block we throw a new exception. So the method in which I call myFunction should provide some mechanism to handle this myException? So the execution will transfer to the catch block of the calling method.Right? So what will happen to the "finally" block of myFunction() ? it won't be executed then? How the flow of program takes place? I am really finding hard what happens when we use "throw". What really happens when we use it?

Was it helpful?

Solution

See (your modified example):

try {
  // Some code ...
}
catch(SomeException e1) {
  // SomeException code ...
}
catch(SomeOtherException e2) { // SomeOtherException is NOT SomeException extension
  throw new myException("whatever message required");
}
finally {
  // Some final code ...
}

Execution Possibilities:

 1. No exception at all:
   Some code executed
   Some final code executed
 2. SomeException is thrown:
   Some code (may be partially) executed  
   SomeException code executed
   Some final code executed
 3. SomeOtherException is thrown:
   Some code (may be partially) executed
   Some final code executed
   throw new myException("whatever message required");
 4. SomeStrangeException is thrown 
   Some code (may be partially) executed 
   Some final code executed
   System'll look for other try {} catch {} block to catch SomeStrangeException 

OTHER TIPS

Consider the following example (Basicalliy your example just filled with some real code, it is designed to throw a NullPointerException):

public class Exceptions {

    public static void myMethod() {
        try{
            String s = null;
            s.length();
        }
        catch(NumberFormatException e1){
            System.out.println("Something unexpected happend");
        }
        catch(NullPointerException e2){
            throw new RuntimeException("Exactly what we want happened");
        }
        finally{
            System.out.println("Finally Block");
        }
    }

    public static void main(String[] args){
        try{
            myMethod();
        }
        catch(RuntimeException e){
            e.printStackTrace();
        }
    }
}

The output of which is:

Finally Block
java.lang.RuntimeException: Exactly what we want happened
    at Exceptions.myMethod(Exceptions.java:14)
    at Exceptions.main(Exceptions.java:23)

So you can see, that the finally-block is executed before the new RuntimeException is handed to the calling method. Otherwise the "Finally Block" output would be after the stacktrace of the RuntimeException.

"Method in which I call myFunction should provide some mechanism to handle this myException?" It should, but the compiler will make you to do that only if myException extends checked exceptions. Whatever will happen, finally block will always be executed.

Everything you can ever want to know about how Java's exceptions are handled at runtime can be found in the Java Language Specification, section 11.3

Essentially, when an exception is encountered, program flow halts and control is transferred up the call stack either until the exception is caught in by a try/catch or until the exception reaches the bottom of the stack, at which point the thread is terminated.

So in other words, "Something occurred, stop whatever you were doing, go to nearest catch block that matches this exception, unless no catch block exists, in which case kill the thread"

In your case, e2 will never occur, because all exceptions are already caught by the first catch block. Multiple catch blocks are generally used if you want to handle different exceptions differently, e.g. catch IOException in one block and NumberFormatException in another, if you were parsing numbers from a file, for example.

You do not have to handle runtime exceptions (exceptions that extend RuntimeException). You do have to explicitly handle checked exceptions (exceptions that extend Exception but not RuntimeException).

The code in the finally block gets executed regardless of whether an exception was thrown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top