Home > front end >  Handling a custom exception without changing the test class (java)
Handling a custom exception without changing the test class (java)

Time:07-28

I need to throw a couple times a custom exception. A test class is checking if my solution works but I'm not allowed to make any changes to this class which leads me to my problem. I simplified the problem here, because the whole code is not needed here

public class Test{
    public static final String s = "0test";
    
    @Test
    public void testZero(){
        Solver sol = new Solver(Parser.run(s));   
        //IntelliJ is underlining "run" because "Unhandled exception: ParseException", a 
        //simple solution could be adding "throws ParseException" in the head, but I'm not
        //allowed to change the test class
    }
}
public class Parser{
    public static Pars run(String input) throws ParseException{
        if(input.charAt(0) == '0'){
            throw new ParseException("...");
        }
    } 
}
public class ParseException extends Exception{
     public ParseException(String mess){ 
         super(mess);
     }
}

CodePudding user response:

I'm not allowed to make any changes to this class which leads me to my problem.

There is no way that you can throw an Exception to the Test class without catching it over there.

BUT you can prematurely just catch it inside the Parser#run(String input).

Instead of this:

public static Pars run(String input) throws ParseException{
    if(input.charAt(0) == '0'){
        throw new ParseException("...");
    }
}

You could (as I said) catch it in the method instead.

public static Pars run(String input) {
    try {
        if(input.charAt(0) == '0'){
            throw new ParseException("...");
        }
    } catch (ParseException e) {
        // System.out.println(e.toString());
        // Just handle it over here if you can't edit Test.java ...
    }
}
  • Related