Handling Exceptions Using Superclasses in Java
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.
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).
OHHH
Updated on June 04, 2022Comments
-
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 calledExceptionB
andExceptionC
, whereExceptionB extends ExceptionA
, andExceptionC extends ExceptionB
. Develop a program to prove that the catch block for the typeExceptionA
catches exceptions ofExceptionB
andExceptionC
".I do not understand how to do this.
-
madth3 over 11 yearsWell, it's impossible to create a superclass of
Exception
so that should a subclass. Appart from that, docs.oracle.com/javase/tutorial/essential/exceptions/index.html
-
-
OHHH over 11 yearsI 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.