sirio sirio - 1 year ago 55
Java Question

demonstrate custom exceptions inheritance java

I have been requested to demonstrate the use of inheritance on custom exceptions. This is what I have been asked:
create a class called MyException:
- Using inheritance, create two exception classes: Exception1 and Exception2;
- Each class should have appropriate constructors that when used they provide a relevant message, such as, “exception 1” and “exception 2”, respectively;


enter image description here

so I created MyException, which inherits from java.lang.Exception:

public class MyException extends Exception{

//default constructor
public MyException() {}

//constructor that accepts a message
public MyException(String message){
super(message);
}


I then create Exception1 and Exception2, but they are empty

public class Exception1 extends MyException {

}


public class Exception2 extends MyException {

}


Despite it works, I think my approach is not correct.
Here is how I test it.

//demonstrate use of custom exceptions
try{
if(true) {throw new Exception1();}
}catch (Exception1 e){
System.out.println("exception1 thrown");
}

try{
if(true) {throw new Exception2();}
}catch (Exception2 e){
System.out.println("exception2 thrown");
}


How can I do this correctly? What should I put into the Exception1 and Exception2 classes?

Answer Source

You should not print what Exception was thrown, but rather print the Exception.getMessage() result, otherwise there's no point in the Exception having a message in this case.

try{
    throw new Exception1("This is thrown intentionally");
}catch (Exception1 e){
    System.err.println(e.getMessage());
}

You you can also add custom methods or additional messages inside of your exceptions, or ,for example, they could be extended from a more specific Exception (better practice).

There is not much more to it than this.

Example of custom exception:

public class MyException extends Exception {

 public MyException() {

     super();

 }

 public MyException(String msg){

    super(msg);

 }

 public MyException(String msg, Exception cause){
     super(msg, cause);
 }

 public static void main(String[] args) {

     try {

         throw new MyException();

     } catch (Exception e) {

         System.err.println(e.getMessage());
     }
 }

}