stackerstack
stackerstack

Reputation: 265

Java throw exception custom message?

I know you can throw exceptions with custom messages using try-catch blocks, such as:

try {
   process...
} catch (IOException e) {
   throw new IOException(..)
}

But if we have a method in a utility class like:

public void processFiles() throws IOException {
   ...
}

and then we pass into the service class like:

public void method() throws IOException {
   Response response = new Response()
   try {
      UtilityClass.processFiles()
   } catch (IOException e) {
      response.setMessage("Error processing files: " + e.getMessage());
      return new ResponseEntity<Response>(response, HttpStatus.INTERNAL_SERVER_ERROR); 
   }
} 

Is there a way to custom set the message from the utility class method processFiles() with its throws IOException, not using a try-catch block inside of that method?

Upvotes: 0

Views: 2278

Answers (1)

Andy Turner
Andy Turner

Reputation: 140328

You can't set the message, but you can create a new exception, with the desired message, and the same stack trace:

} catch (IOException e) {
  IOException ee = new IOException ("your message");
  ee.setStackTrace(e.getStackTrace());
  throw ee;
}

Of course, this throws it as an IOException, rather than a subclass, if e is, say, a FileNotFoundException, so it doesn't quite achieve the same effect.

Upvotes: 1

Related Questions