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?
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.
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With