(3) Checked Exceptions

  • As we discussed before,not handling checked exceptions would lead to compilation failures,unlike runtime exceptions
 public static void main(String[] args) {
        throw new Exception();
         }


This is CE (for here onwards,I'll refer it CE=compilation error:P )
  • Creating Exceptions,

 
  •   See throws clause as a filter (like we saw try - catch as nets ).They inform an exception may come.

 

  • Q)
public class ExceptionEg {
   
    static void A() throws Exception{
        System.out.print("A");
        throw new Exception();
    }
    static void B(){
        System.out.print("B");
        A();
        System.out.print("C");
    }
   

    public static void main(String[] args) {
        try {
            System.out.print("D");
            B();
            System.out.print("E");
           
        } catch (Exception e) {
            System.out.print("caught");
        }
       
    }
}


what would be the output?

Output would be D B A then CE.
So how can we avoid the CE? simply adding a filter (throws clause) at B method or putting a net (try - catch block) at  A or B methods.
  
  • What happens at method overriding then? Easy,two simple rules
If the superclass method does not declare an exception 
*   If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.  
If the superclass method declares an exception 
*   If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 


  •  You get an ExceptionInInitializerError if something goes wrong in the static initializer block.

    class C
    {
      static
      {
         // if something does wrong -> ExceptionInInitializerError
      }
    }
 So hope that this wraps up all the necessary important points that a java developer should know when it comes to exception handling :)





Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment