Reputation: 23
I am a newbie and learning Java exceptions,
public void function (argument) {
if (condition) {
throw new Exception;
}
}
My confusion is:
If I know like the condition will cause NullPointerException, so I can throw a NullPointerException.
What if the code throw some Exceptions I didn't expect, or say I don't know what is the Exceptions of my code, what should I throw?
Like this link When to throw an exception? said: "Every function asks a question. If the input it is given makes that question a fallacy, then throw an exception."
but if the input does make a question a fallacy, but myself don't know this input will cause this fallacy, what should I throw?
Or I should run enough test to find all exceptions and throw them?
I know my question is weird, but if you know what am I saying, please give me some instructions. Thanks
Upvotes: 0
Views: 123
Reputation: 1517
Source: Oracle - The Java Tutorials - "What Is an Exception?":
"After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.".
Each function that doesn't directly provide a means to handle an exception returns to a caller with either a successful result or an unhandled exception for the caller to handle.
A function that might encounter an exception and is able to handle it avoids the need to have the caller handle it, similarly a caller that can handle exceptions from its subroutines saves writing the handler in the subroutines.
If the caller is calling various subroutines that might all encounter the same error conditions then handling it in the caller results in less code (and consistency in the handling of the exception) over rewriting similar code in each subroutine which would be better handled by the caller.
Source: Oracle - The Java Tutorials - "Unchecked Exceptions — The Controversy":
"If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.".
Try to predict what could happen and handle it if possible, always trying to let the caller do the work if it's duplicated in multiple callees and having the 'leaves of the tree catch the light work'.
Or I should run enough test to find all exceptions and throw them?
Writing a test harness can be separated or part of the code, if it's internal then usually (but not always) you'd want to define it out of the release version.
Upvotes: 1
Reputation: 630
I think an exception should be thrown:
if a function cannot satisfy an established condition
it cannot satisfy the precondition of a function it is about to call
if this can cause instability for other members
There are some other situations that can be taken into consideration, but basically for me these are the main things to keep in mind.
Upvotes: 0