简体   繁体   中英

Difference between “throw(e)” and “throw e”?

I came across this rethrown exception and am surprised that it even compiles.

} catch(SomeException e) {
    ...
    throw(e);
}

Is there any difference between this throw() and what is normally used?...

} catch(SomeException e) {
    ...
    throw e;
}

Any links to where this is documented or guidance on choosing one over the other?

Quite a few languages allow as many parenthesis around expressions as you want. Java is one of them. The following is perfectly valid code.

public class HelloWorld {
  public static void main(String[] args) {
    throw ((((new RuntimeException()))));
  }
}

So there's absolutely no difference, except that your source file is two bytes larger.

Functionally they are equivalent.

However, don't choose throw(e); , as someone might mistake it for a method call, and the very least will make someone unnecessarily wonder what it is that you're doing. Prefer the normal throw e; syntax for clarity.

Throw is an instruction to throw a "throwable" (usually an exception)

Think if it like a return statement

Public int get value() {
    return 3;
}

Is equlivilant of

Public int get value() {
    return (3);
}

It's the same with throwable.

In face they will complied to the exactly same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM