Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you throw anything in Java? [closed]

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?

like image 790
Johanes Matian Avatar asked Mar 04 '13 11:03

Johanes Matian


People also ask

Is it possible to throw any Java object?

For now, all you need to remember is that you can throw only objects that inherit from the java. lang. Throwable class. Note that the declaration of the pop method does not contain a throws clause.

Does Throw in Java stop execution?

When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.

What exceptions can you throw in Java?

We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.

Can we throw exception in try block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.


1 Answers

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.

like image 182
Stephen C Avatar answered Nov 01 '22 03:11

Stephen C