Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Exception Junit

I cannot run my test because the test gets red squiggly error line in this statement decorator.decorate(new EncoderColumnDecorator()) requiring me to use either try/catch or add throws. This is the error message. enter image description here

Why do I have to put either try/catch or throws exception when I already have an attribute "expected"

My unit test:

@Test(expected=DecoratorException.class)
    public void testDecorate_exception() {
        decorator.decorate(new EncoderColumnDecorator()); -----Error in this line
    }

Method under test

@Override
    public String decorate(Object arg0) throws DecoratorException {
        try{
                //some code     
            }
        }catch(Exception e){
            throw new DecoratorException();
        }       
        return arg0;
    }

}
like image 836
Nero Avatar asked Jan 08 '16 18:01

Nero


1 Answers

That is simply the rule that has to be followed for the code to be valid Java. If a function calls another function that throws then it must either also throw that exception or it must catch it.

It is a bit like static typing of variables. While it may seem inconvenient it can help ensure correct code by not allowing ambiguity. Having the compiler report any inconsistency helps with detecting problems much earlier.

like image 87
PeterSW Avatar answered Nov 15 '22 05:11

PeterSW