I just cannot figure out the syntax error saying: "This method must return a result of type byte[]" at where I do have a byte[] return type specified.
It doesn't mean that you have to declare it to return byte[]. Clearly you already did that. It means that the code must always return a result of type byte[], and your code doesn't always do that.
Figured it out? Good! But I'm curious about what you did to fix the problem. I have a solution in mind and I'd be interested to see if it's the same as yours.
OK, going into a bit more detail - in your last example, if any exception is thrown then xslt will still be null. Which means that when you reach line 16, you're going to get a NullPointerException thrown.
The question you need to ask yourself is: what do I want the method to do in case of error? I reckon there are three plausible options.
1. Return null
2. Return an empty array
3. Throw an exception
Paul's suggestion is to go for option 3. In that case you just throw the exception up to the calling code, and let it decide what to do. This looks sensible to me because the calling code is going to have a better idea about what should be done in the event of error. This utility method doesn't really know enough about the context to know what to do next.
If you want to use 1 or 2, you can do that with a small modification to your code, but you need to allow for the problem I pointed out above.
(By the way - where is the url variable coming from? I'd suggest that should be passed into the method as an argument rather than reliying on a static variable - unless it's a constant).
I have been coding but do not really understand how to deal with exceptions. Fortunately, I came to the Forum and raised a question about my code. I can see better now.
The "url" is the location of a XSL file. Is it qualified to be a constant?
Natalie Kopple wrote:Sorry, I do not know why. And I cannot answer "what to return in case that an exception is thrown?"
Then that's why. If you don't know what to return from a method if an exception is thrown, then that method isn't qualified to handle exceptions. So it shouldn't handle exceptions. Hence my code.
Natalie Kopple wrote:The "url" is the location of a XSL file. Is it qualified to be a constant?
I can't tell you. That entirely depends on the application. Is it always going to be the same XSL file? Are you happy having to recompile the application in order to use a different file location? If not, then no, it shouldn't be a constant.
I suggest huckleberry pie. But the only thing on the gluten free menu is this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss