Reputation: 24857
I would like to throw a custom exception that will be determined at runtime. Currently I have to either add throws to the function or surround it with a try catch. What I want is for this exception to not be caught at all. It is a fatal exception and will show the programmer the error and what he can do to fix it. This is for an abstract class checking if initialization has been run first. I would like it to act like a NullPointerException, as when it occurs the program crashes.
Thanks
Upvotes: 7
Views: 2604
Reputation: 12287
Subclass RuntimeException instead of Exception.
I obviously don't know the design decisions behind this, but it seems like there may be a better way to achieve whatever you're trying to do.
Upvotes: 18
Reputation: 75376
You should create a base exception (perhaps named Boobake4DomainException
) extending RuntimeException
, and then extend that for all your runtime exceptions.
Then you can just } catch (Boobake4DomainException e) {
to be certain upstream if it is one of your own or not. This can make your problem handling code much simpler.
Upvotes: 0
Reputation: 76709
You need unchecked exceptions, or exceptions that extend the RuntimeException
class. By default, all unchecked exceptions are eventually caught by the default uncaught exception handler that prints the stack trace of the exception. Unless you have modified the default uncaught exception handler to be a different one, the behavior you observe on throwing unchecked exceptions will the same as the one you encounter when a NullPointerException
(another unchecked exception) is thrown.
Note, that you will not see an exception stack trace if the unchecked exception is caught by a caller that acts on it without printing the stack trace. There is no difference in the manner in which unchecked and checked (those extending Exception
instead of RuntimeException
) exceptions are caught; there is only a difference in which the compiler treats checked and unchecked exceptions.
Upvotes: 0
Reputation: 8319
Your program should never just crash.
It should ideally log the backtrace and any related info that would help to debug the issue, and then exit notifying that something went wrong and where the details are logged.
Upvotes: 2
Reputation: 1912
Make your custom exception a subclass of RuntimeException
. These may be caught in a try/catch but this is not enforced by the compiler.
Upvotes: 3