0

Similar to Multiple exception catch block java 8 eclipse SO question, I have the same issue. The referenced question does not really provide a solution, though.

In a JAX-RS web service, I am trying to build a stream. Inside the stream, I am running a query and will write the results to the stream.

Here is my working code:

public StreamingOutput getExportData (int year_mo, String plant, String reqType, String payType) {
    StreamingOutput stream = new StreamingOutput() {

        @Override
        public void write (OutputStream output) throws IOException, WebApplicationException {

            PrintWriter out = new PrintWriter(new OutputStreamWriter(output));

            ...

            try (AdbDao dao = new AdbDao();) {
                ResultSet rs = dao.getExportData(year_mo, plant, reqType, payType);

                ...

               if (rs != null) {
                    while (rs.next()) {
                        ...
                    }
                }
            } catch (JSONException | SQLException e) {
                e.printStackTrace();
                throw e; <-- This is the issue
            }

            output.flush();
            output.close();
        }
    };

    return stream;
}

The throw e; produces the message Unhandled exception type SQLException

What do I need to do to be able to throw the exception back to my web app?

Paul Stoner
  • 1,359
  • 21
  • 44
  • If you don't want an SQLException to be thrown, what else do you want to be thrown? – Thomas Weller Jul 25 '19 at 20:40
  • Side note: IMHO, you should really have a `finally` block for the `.flush()` and `.close()`. – Thomas Weller Jul 25 '19 at 20:41
  • An `SQLException` is a checked exception, that means that if you throw it, you must declare it to be thrown using the `throws` clause. You're throwing the `SQLException` within the `write` method, but this method does not declare an `SQLException` to be thrown. That's why you can't do this. Either wrap your exception in an unchecked exception, or within one of `IOException` or `WebApplicationException`. – MC Emperor Jul 25 '19 at 20:42

1 Answers1

0

You need to either

  1. declare your method throws SQLException
  2. handle it in catch block (and dont rethrow it)
  3. or wrap it in eg RuntimeException and throw that - or any other exception that suits your needs.
Antoniossss
  • 31,590
  • 6
  • 57
  • 99