❮ Previous Next ❯

Java ExceptionHandling with MethodOverriding

There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:

  1. If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
  2. import java.io.*;
    class Test
    {
    void print()
    {
    System.out.println("in print");
    }
    }
    class TestExceptionChild extends Test
    {
    void print()throws IOException
    {
    System.out.println("in sub class");
    }
    public static void main(String args[])
    {
    Test t=new TestExceptionChild();
    t.print();
    }
    }
    Output

    Compile Time Error

    Let's see the following program where in sub class the method throws an unchecked exception:

    Example

    import java.io.*;
    class Test
    {
    void print() {
    System.out.println("in print");
    }
    }
    class TestExceptionChild extends Test
    {
    void print()throws NullPointerException
    {
    System.out.println("in sub class");
    }
    public static void main(String args[])
    {
    Test t=new TestExceptionChild();
    t.print();
    }
    }
    Output

    in sub class

  3. If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
  4. import java.io.*;
    class Test
    {
    void print()throws ArithmeticException
    {
    System.out.println("in super class");
    }
    }
    class Child extends Test
    {
    void print()throws Exception
    {
    System.out.println("in sub class");
    }
    class TestChild
    {
    public static void main(String args[])
    {
    Test t=new Child();
    try
    {
    t.print();
    }
    catch(Exception e){}
    }
    }
    Output

    Compile Time Error


❮ Previous Next ❯


  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved