9

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; } } 
1
  • 4
    The method throws an exception, requiring any method that uses it to throw/try...catch it as well. This includes JUnit methods. Commented Jan 8, 2016 at 18:27

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.