sabato 5 maggio 2012

try / catch flow control in java

When exception occurs flow control passes to catch block and than continues to finally or whatever is after catch. See this sample code


public class testTryCatch {

  public static void main (String args [] ) {
     
      try {
          Long.valueOf("a");
          System.out.println("never printed");
      } catch (NumberFormatException e) {
          e.printStackTrace();
      }
      
      finally {
          System.out.println("finally");
      }
      System.out.println("after catch / finally");
      try {
         long l =  Long.valueOf("34a");
         System.out.println(l);
      } catch (NumberFormatException e) {
          e.printStackTrace();
      } 
    }
}



Program OUTPUT IS

java.lang.NumberFormatException: For input string: "a"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:410)
    at java.lang.Long.valueOf(Long.java:525)
    at testTryCatch.main(testTryCatch.java:9)
finally
after catch / finally
java.lang.NumberFormatException: For input string: "34a"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:419)
    at java.lang.Long.valueOf(Long.java:525)
    at testTryCatch.main(testTryCatch.java:20)


ANOTHER SAMPLE WITH RETURN



public class TestException {

   
   
   
    public static void main (String [] args) {
        System.out.println(demoMethod("10"));
      
        System.out.println("end first call ");
      
        System.out.println(demoMethod("10a"));
      
    }
   
   
   
    public static int demoMethod(String intString) {
        try {
            Integer pippo = Integer.valueOf(intString);
            //never reached
            return pippo;
   
        } catch (NumberFormatException ne) {
            ne.printStackTrace();
            return 0;
        } finally {
            System.out.println( "finally reached");
            return 1;
        }
      
    }
    

OUTPUT

finally reached
1
end first call
finally reached
1
java.lang.NumberFormatException: For input string: "10a"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:458)
    at java.lang.Integer.valueOf(Integer.java:554)
    at TestException.demoMethod(TestException.java:20)
    at TestException.main(TestException.java:12)


Nessun commento:

Posta un commento