Can't rethrow exception in a function

Answered

I want to rethrow an  exception in a function like:

int foo()
  try {
    // do sth
    return 0;
  } catch (Exception e) {
    bar(e);
  }
}

void bar(Exception e) {
  // prepare for rethrow
  throw e;
}

IntelliJ complains that foo is missing return statement. The reason I want to rethrow in bar is reducing code repetition as many other places also need to call bar(). Is it a bug of IntelliJ?

0
1 comment

Hello,

The code sample provided is uncompilable with Javac. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under Throwable is checked. Exception extends Throwable, so the method must either handle the exception or it must specify the exception using throws keyword. That's the first error, second is missing return statement. IDEA's highlighting works correct in your case.

The compilable variant of code will look somehow like this:

int foo()
throws Exception {
try {
// do sth
return 0;
} catch (Exception e) {
bar(e);
}
return 1;
}

void bar(Exception e)
throws Exception {
throw e;
}

But seems that it's not reasonable to create here an extra method.

0

Please sign in to leave a comment.