Tuesday, March 15, 2016

Java : Exceptions (try catch)


Java : Exceptions (try catch)



1. Creating and Catching an Exception
    public void crossFingers()
    (
        try{
            Object.takeRisk();
        ) catch (BadException ex) // "ex" can be any variable
            System. out.println ("Aaarqh! ") ;
            ex .printStackTrace () ;
        }
    }

    public void takeRisk () throws BadException {
        if (abandonAllHope) {
            throw new BadException();
        }
    }

---------------------
2. A finally block - runs regardless of an exception or even if the catch has a return statement
   
    try (
        turnOvenOn();
        x.bake () ;
    }catch (BakingException ex)
        ex.printStackTrace();
    }finally { //
runs regardless of an exception or even if the catch has a return statement        
turnOvenOff();
    }

   
3. Multiple try catch

    try {
        throw new IOException();
        }catch (FileNotFoundException f){
           
        }catch (IOException  e){
            System.out.println(e);     //output :     java.lang.NullPointerException
            e.printStackTrace;        //output :    java.io.IOException at package.Test.main(Test.java:74)
                                   
        }catch (Exception e){        //Catches all sorts of Exception should be placed LAST
                                    //If passed 1st any catch block belowing will be skipped
        }finally{
        }

       
4. Multiple catch Using OR (|)
        try {
        do something ;
        }catch (FileNotFoundException | IOException e){ //Catch executes when either of the 2 exception occur
       
        }

       
5. What you can do inside catch block ?
    -    e.printStackTrace()
    -    e.getmessage();
    -     log.error("Ops!", e); //Using logging framework like logback or log4j
    -     "USER CAN DO ANY OPERATIONS"
   
6. What is Throwable t ?
    -    In normal cases we should always catch sub-classes of Exception.
   
    Example :
        try {
        do something ;
        catch(throwable t){ //"throwable" is super class of exception
           
        }

   
   

3 comments: