Why can you throw anything in Java? [closed]
Asked Answered
R

1

9

In Java theoretically you can throw only Throwables.

This is allowed by the language and checked during class-loading. But if you disable class checking

java -Xverify:none -cp . BadClassThatCompiles

then you can run a class that throws any class (not derived from Throwable) (Example)

Why?

Why is it designed this way .. meaning a virtual machine that allows throwing objects and a verifier that has to filter out wrong code. As if some code could be wrong. It's not the code, it's the design!

Why?

Richela answered 4/3, 2013 at 11:5 Comment(3)
Why what ? Why does disabling the verifier lets you do strange things ?Kenning
why the JVM allows throwing objects ?!Richela
@dystroy - it allows you to load bytecode files that break various rules that are designed to protect the JVM from corruption; e.g. returning an object from a method that doesn't match the expected return type. It is like juggling with loaded pistols ... a really bad idea.Tame
T
4

Why is it designed this way .. meaning a virtual machine that allows throwing objects and a verifier that has to filter out wrong code. As if some code could be wrong. It's not the code, it's the design!

Why?

Simply because the design works from almost all perspectives.

Well what would the alternative be?

I guess you would have to have a special kind of "things" that were NOT instances of classes that were designed for the sole purpose of being thrown.

That would require:

  • a new syntax for defining these exception non-objects
  • a whole new set of typing rules to handle these non-objects (for instance they cannot be assignment compatible Object ...)
  • and so on.

At the end of the day, the Java language would be more complex, and harder to use for the programmer. And to what end? To slightly simplify the task of the verifier?

Sorry, but if you take it to its logical conclusion, this idea is a non-starter.


And frankly, who cares if you can break the JVM by disabling the verifier. Its like complaining that you can shoot yourself if you juggle loaded pistols.

Tame answered 4/3, 2013 at 11:19 Comment(4)
Why not just allow throwing anything in the language? It all seems like a bad design / requirements mismatch...Richela
@JohanesMatian I think if you take any language I'll find many hacks and different way-arounds. There are no flawless platform or language.Telescopy
@StephenC - the question is: "why". This is very constructive.Richela
As suggested, I have cleared the comment thread (or at least my part of it).Tame

© 2022 - 2024 — McMap. All rights reserved.