Reputation: 31
I opened Exception
subclass like NullpointerException
class, it had constructors & no other methods. How does the JVM know the cases in which such exception is to be shown ?
Upvotes: 2
Views: 72
Reputation: 2775
There's a couple of exceptions that the JVM will throw automatically in specific situations. NullPointerException, or OutOfMemoryError are amongst them.
Because sun/oracle has defined their exact purpose, the logic of when to throw them is coded into the JVM itself. (e.g. in case your application requires more memory than is available, the JVM knows it has to throw an OutOfMemoryError; in case you try to access a field or method of a null object, it knows it has to throw a NullPoinerException).
These rules are clearly specified and codified in the JVM.
In that case they differ from any "custom" Exception that you'd create for your own use. Obviousely, the JVM does not know about their semantics and will never automatically throw them. Instead you have to throw them yourselves.
BTW: in case you wonder, why you don't need try/catch blocks for NullPointerException: this is because they inherit from RuntimeException. By definition, any exception inheriting from RuntimeException does not need to be declared or explicitely caught. (you can declare and catch them explicitely but that's optional)
Hope this helps :) Matthias
Upvotes: 5