Why would I extend java.lang.RuntimeException
I was recently asked a question, apparently in an Interview, about extending the java.lang.RuntimeException.
I was asked to cite an example where there would be a need to extend the java.lang.RuntimeException.
I always thought that we would not need to extend the RuntimeException, can anybody enlighten me?
Thanks, SB开发者_JS百科
One layer's runtime exception is another layer's checked (and acted upon) exception.
I can see containers e.g. servlet container; REPLs and/or anything top-level interpreter loop; etc. legitimately selecting and catching RuntimeExceptions as they are not supposed to crash simply because something goes boom deeper in the stack.
Similar to the container case, crossing adjacency boundaries e.g. crossing layers or tiers typically calls for a more articulated exception semantics.
If the 'cause' and/or message properties prove semantically insufficient to express anything beyond "hey, it broke", and the client/higher layer can act selectively, then it is arguably legitimate to sub-class RuntimeException.
You want to extend RuntimeException when you create an Exception that doesn't have to be explicitly caught (unchecked exception). This is the case of exceptions that signal a problem that normally can not be recovered (eg. a dead database).
You should take a look at the difference between checked and unchecked exceptions in Java.
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
See RuntimeException
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
If you add new feature to the jdk or if you modify the jvm implementation you should extend the RuntimeException in order to add new RuntimeException.
You should stay with the these that this exception should not be extended, because it should be used usually in places where no more action can be executed and operation should be interrupt.
But if You rally need to find out a application for that case, you can say that by creating different type of RuntimeException we can have more control in out exception handler to display the messages of exception etc. but IMHO this is only a play talk.
when the client cannot reasonably recover from program,i would throw Runtime Exceptions, these are typically Unchecked Exceptions, mostly bugs in code, where the client is not expect to recover at runtime
examples: dead link to data source, JNDI binding failure, pre condition failed for certain operations(division where the denominator is zero) are scenarios for this RuntimeException subclassing
精彩评论