Home > Software engineering >  Custom Exception handling several error messages
Custom Exception handling several error messages

Time:11-19

I am learning Java at the university. I am trying to solve a problem but I'm not finding the solution. Hope you can help!

I have to build a subclass that is inheriting from the java class Exception to create a custom exception. In this subclass, I have to define 4 different error messages. In another class, there are 4 methods that will call the subclass whenever they throw an exception. Depending on the method a different error message needs to be selected. How can I do that? How can I select the right message based on the function that throws the error?

Thanks in advance,

public class CustomException extends Exception{

    public String EXCEPTION_NAME = "[ERROR] Name cannot be longer than 10 characters";
    public String EXCEPTION_YEAR = "[ERROR] Year cannot be later than current year";
    public String EXCEPTION_DESCRIPTION = "[ERROR] Description cannot be longer than 50 characters";
    public String EXCEPTION_PRICE = "[ERROR] Price cannot be negative";

    public CustomException(){
        super();
    }

    public CustomException(String msg){
        super(msg);
    }
}

CodePudding user response:

The code creating the exception could pass the message to the exception constructor:

if (price < 0) {
    throw new CustomException("Price is negative!");
}

Or, if you feel that this code shouldn't know about the exception message, you could use dedicated exception classes:

if (price < 0) {
    throw new NegativePriceException();
}

and

class NegativePriceException extends CustomException {
    NegativePriceException() {
        super("Price is negative!");
    }
}

CodePudding user response:

Add the static and final words to your EXCEPTION strings. Then you can access them outside of the class. After that, you can throw your CustomException with your own message. For example;

throw new CustomException(CustomException.EXCEPTION _PRICE);

Or I suggest that you create a new class for each exception and throw it. For example;

class PriceNegativeException extends Exception {
    
    public PriceNegativeException() {
       super("[ERROR] Price cannot be negative");
    }

}

and than throw that in your method;

throw new PriceNegativeException();

This is a better approach for Exception Handling;

  •  Tags:  
  • java
  • Related