-1

I have this code:

try {
//  if (false) { //(need to add this, otherwise it doesn't compile)
//      throw new CountDownExc(-1);
//  }

    return ad2;
} catch (StackOverflowExc | NoClassDefFoundError e) {
    throw new CountDownExc(50);
} catch (CountDownExc e) {
    if (!e.surfaced()) {
        e.dec();
        throw e;
    }
    return 0.0;
}

And if I don't add the commented code it doesn't compile with a:

error: exception CountDownExc is never thrown in body of corresponding try statement

Why?

Most of all, why does the first catch doesn't cause the compiler to complain (but the second block seems to be wrong)

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
BamDoya
  • 73
  • 7
  • "CountDownExc is never thrown in body of corresponding **try** statement" emphasis should explain why it doesn't like it there. About the fact that it complains only about `CountDownExc` I suppose `CountDownExc` is a checked exception, while the other two aren't – Federico klez Culloca Jun 07 '22 at 09:00
  • I think you expect the throw in the first catch to make the second catch valid? If so, then no, all the catches refer just to what's in the `try` block. – RealSkeptic Jun 07 '22 at 09:16

1 Answers1

1

There is a couple of problems with your code:

  1. First and foremost you need to understand the difference between checked exceptions and unchecked exceptions: Understanding checked vs unchecked exceptions in Java

Essentially you need to consider checked exceptions as part of your logic and you can only either rethrow them or handle them via catch. The only other option if you need to avoid catch( CountDownExc ) is to add a throws CountDownExc declaration to your method.

  1. These lines make little sense to me:
} catch (StackOverflowExc | NoClassDefFoundError e) {
    throw new CountDownExc(50);

It looks like you intend on catching two exception types in the first catch block, throw CountDownExc in that first catch block, then handle it in the second catch block. That's not gonna fly, because catch blocks handle what is thrown in a try block, not in a catch block. Since CountDownExc is a checked exception this is going to result in another compilation error, unless you either wrap your try-catch in another try-catch (bad practice) or add a throws declaration.

Since both of your catches throw CountDownExc the exception will have to be handled elsewhere anyway, so this may already be accounted for - I cannot tell, because the rest of your code is unknown.

Your immediate problem however comes from the fact, that nothing in your try block is able to throw CountDownExc and CountDownExc is a checked exception, see first link.

Koenigsberg
  • 1,726
  • 1
  • 10
  • 22