0

the method below was compiled without any compilation Error on Eclipse Using JDK 7; Strangely the same method on Inellij IDEA 14 with the same JDK 7 produce a compilation error, but it Run! Is this due to a bad configuration on my IDEA? Thanks :)

  static void testException() throws FileNotFoundException, SQLException {
    boolean zx = false;
    try {
      if (zx) {
        throw new FileNotFoundException("1");
      }
      else {
        throw new SQLException("2");
      }
    }
    catch (Exception ex) {
      throw (ex);
    }
  }
arammal
  • 393
  • 1
  • 4
  • 11
  • The method doesn't throw `FileNotFoundException` or `SQLException`, it throws `Exception` – Ryan J Apr 13 '15 at 02:55
  • 1
    actually this shouldn't even compile. you haven't specified `Exception` as possible exception. and btw. this snippet doesn't implement multicatch. –  Apr 13 '15 at 02:56
  • If you remove the `()`'s from `throw (ex)` and if actually compiled with Java 7 (language level 7 as well), then it should work as written. – Ryan J Apr 13 '15 at 03:02
  • multicatch comes with `|` operator in catch block. – Vinayak Pingale Apr 13 '15 at 03:06
  • If working with JDK 6 rethrowing using this way will produce an Exception. But in JDK 7 there is a new functionality that let you replace the (FileNotFoundException | SQLException e) by (Exception e) and the compiler is smart enough to understand that here the "Exception" is just replacing "FileNotFoundException | SQLException e" and this is what I was trying to test in this method. You can try to compile this code directly using javac (JDK 7) it will compile and run without any problem. – arammal Apr 13 '15 at 03:58
  • @arammal no, this code will not compile as-is (even with Java 7). You have a slight issue with the syntax re: the `throw (ex)`, which will cause the compiler to report that you have not declared `Exception` as a throwable by this method. If you remove the `()`'s and use `throw ex` then it will work. You need to fix your code. – Ryan J Apr 13 '15 at 07:01
  • thanks Ryan J it works now. It was the parenthesis! – arammal Apr 13 '15 at 13:44
  • @Ryan J you know why the parenthesis matter? is that a java thing or Intellij thing? – Xinchao Dec 23 '15 at 02:23
  • @Xinchao don't know the exact reason, but it's a Java thing. The syntax differs in that the ()'s cause the exception to be interpreted literally as type `Exception`, where without the () it will be thrown as one of the declared types (since the only way to enter that catch block is to be an instance of either exception type that was declared). – Ryan J Dec 23 '15 at 03:23

0 Answers0