Handling Exceptions Using Superclasses in Java

11,340

Solution 1

Here is a very simple code. You can further enhance for your learning.

Create exception ExceptionA and define require constructors and methods:

    public class ExceptionA extends Exception {

        public ExceptionA(String message){
            super(message);
        }
    }

Create exception ExceptionB and define require constructors and methods:

    public class ExceptionB extends ExceptionA {

        public ExceptionB(String message){
            super(message);
        }
    }

Create exception ExceptionC and define require constructors and methods:

    public class ExceptionC extends ExceptionB {

        public ExceptionC(String message){
            super(message);
        }
    }

Create TestException class which catches ExceptionB and ExceptionC using ExceptionA as below:

    public class TestException {

        public static void main(String[] args){

            try{
                getExceptionB();
            }catch(ExceptionA ea){
                ea.printStackTrace();
            }

            try{
                getExceptionC();
            }catch(ExceptionA ea){
                ea.printStackTrace();
            }

        }

        public static void  getExceptionB() throws ExceptionB{
            throw new ExceptionB("Exception B");
        }

        public static void  getExceptionC() throws ExceptionC{
            throw new ExceptionC("Exception C");
        }

    }

Solution 2

Pretend that this is a family of asexually reproducing things called Exceptions.

Family Tree

Exception C is the son/daughter (what do I even call them) of Exception B, who is the son/daughter of Exception A, who is the son/daughter of Exception. Exception C inherited genes from Exception B, who inherited genes from Exception A, etc.

What your teacher wants you to do is show that you can "catch" Exception C's using the same method to that you are using to "catch" Exception A's. So you would be using try/catch statements and throw statements (to generate the exception).

Share:
11,340
OHHH
Author by

OHHH

Updated on June 04, 2022

Comments

  • OHHH
    OHHH almost 2 years

    For homework, I have to develop an exceptions code:

    "Use inheritance to create a superclass of exception called ExceptionA, and two subclasses of the exception called ExceptionB and ExceptionC, where ExceptionB extends ExceptionA, and ExceptionC extends ExceptionB. Develop a program to prove that the catch block for the type ExceptionA catches exceptions of ExceptionB and ExceptionC".

    I do not understand how to do this.

  • OHHH
    OHHH over 11 years
    I love you, got it now, I did get the inheritance thing before I created this post, but you cleared my doubts about the implementation of the exceptions.