5

While creating custom exceptions, If we want to create a checked Exception we extend the Exception class and for unchecked exception we extend the RuntimeException class. My question is, how JVM handles subClasses of RuntimeException and Exception differently when they all are sub classes of the Exception class.

gaurs
  • 575
  • 1
  • 5
  • 19

2 Answers2

6

It doesn't. The only difference is in requirements enforced by the compiler.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
3

You are mistaken that the JVM handles the exceptions differently, but your question is still valid if you are asking how the compiler treats them differently.

And this has a simple answer: the rule does not state that all subclasses of Exception are checked exceptions. Those which are also subclasses of RuntimeException are unchecked.

William F. Jameson
  • 1,833
  • 9
  • 14
  • Thanks for the reply William, Actually that was my concern. Both the subClasses being instanceof type Exception are still handled differently by the compiler. Moreover you said "the rule does not state that all subclasses of Exception are checked exceptions", but then how come every subclass of Exception(only) is treated as a checked exception. – gaurs Jul 17 '14 at 09:23
  • I don't understand your question: every subclass of `Exception` which is not also a subclass of `RuntimeException` is treated as a checked exception, that's the definition. What do you mean by "how come"? – William F. Jameson Jul 17 '14 at 09:26
  • @gaurs, ""but then how come every subclass of Exception(only) is treated as a checked exception."" it checks if instanceof RuntimeException then -> Unchecked Exception ! else if instanceof Exception then -> Checked Exception ! – Jayanand Raghuwanshi Feb 28 '22 at 14:05