posted 15 years ago
I'm going to answer your question in two ways -- 1: to explain why your code doesn't compile, 2: to explain the proper way to write this method.
1: So as for the first part -- why your code doesn't compile:
When you use the "throw" clause, the method you call needs to return an Exception object
"throw new MyException()" in fact returns an Exception object, but you then chain that method with a call to setErrorMessage() which doesn't return anything, and so you get an incompatible Type error.
There are 2 ways you can fix this.
-- have setErrorMessage() return the MyException object.
-- construct and modify the Exception in one line, and throw the exception in the next line.
2- That being said, this isn't the "proper" way to use and define your own exception, a better way would be to define a constructor that takes the error message as an argument:
and then call the exception like this: