Clear and simple rules for deciding between checked and unchecked exceptions - java

Since there is a lot of ambiguity about this, can we come up with some clear, simple and easy to use rules?
Here is a first try, these three rules should be sufficient for all cases.
First rule is based on the common principle that implementation details of the method should not be exposed to the caller:
Rule 1:
Checked exception should not expose implementation details to the caller:
You can test it this way: If you completely change the implementation but still expect the method to fulfill its contract (like in refactoring) would it still make sense to throw the exception?
If yes then it should be a Checked exception because it is not implementation detail but part of use case the method fullfills.
If no then the exception should be unchecked because it is an implementation detail which should not be exposed to the caller.
If based on Rule 1 the exception should be checked then apply the Rule 2:
Rule 2: Since checked exception is part of the method contract, violation of the method's contract can't be a checked exception.
For example this method executes sql query from its param:
executeSqlQuery(String sqlQuery)
If caller provides string that is not an sql query then he violated input conditions of the method and the resulting exception must be unchecked.
If based on Rule 2 the exception still seems like checked, apply rule three which checks whether the method is following another best practice: single responsibility principle
Rule 3: Method should do just one thing.
For example method
List.get(int index)
is correctly doing just one thing: returning desired element from the list. And not trying to also fulfill another common use cases: check whether the element is present.
On the other hand method
findById(Long id) throws RecordNotFoundException
is incorrectly trying to mix these two functions and by that forces all callers to always consider the use case when record is not found even though they know that the record exists.
Is some rule missing or can we simplify and clarify the rules further?
BACKGROUND:
There are many different views on this topic. There is quite a lot of proponents of "radical" solutions like never to use a checked exception (some java books or designers of C#) or that almost everything should be a checked exception (IOException in java.io package or SQLException in JDBC).
And at least same number of views suggest to use both types but are offering subjective and ambiguous rules for deciding between them which without a lengthy explanation that is often missing instead of helping just bring more confusion (eg: If it is reasonable for the caller to recover from the exception than it should be checked. Is trying the call again a reasonable recovery? For some clients it may be. Words reasonable and recover are too ambiguous.)

Um, that question is answered in the official Java Tutorials, in fact:
Here's the bottom line guideline: 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.
That looks like a pretty clear, simple rule to me.
EDIT: your background edit explains your confusion and frustration quite well. If you want to, I can come up with a even simpler rule:
Always be usable. Try to be practical where possible. Strive to be consistent.
The point is that exception handling is something that the user of the method that might throw must do. Sadly, Java forces the person who writes that method to make the choice for the user of that method. Thus, I'm leaning slightly towards the "never do checked" side, because your methods will always be usable. For some cases, for example network I/O, it might be really practical to force the user to build in some error handling, but that's not really often the case. If you're asking yourself hm, my last 400 methods all threw RuntimeErrors, should this now throw a checked exception?, attaining consistence might make using your library more practical.
Sadly, this rule is easier, but not clearer, because at least practical and consistent are very subjective notions. So here you are, stuck with something that is really a question of style.

The fundamental problem with the way Java handles checked exceptions is that while it would be useful to distinguish exceptions that get thrown for expected reasons (e.g. getRecordById throwing a RecordNotFoundException when given an ID that doesn't exist) from those which get thrown for unexpected reasons (e.g. a method which calls getRecordId for an ID which is supposed to exist, but doesn't), the type of an exception has little to do with whether it's coming from a method for reasons that method knows about, or because it was unexpectedly thrown in a nested method call.
If Java allowed exception instances to be marked as "expected" or "unexpected", with distinct statements for catching expected and unexpected ones as well as a means of indicating that any methods within a block aren't expected to throw certain exceptions (and if any such exceptions that are thrown are marked as "expected", they should be flagged "unexpected" before propagating out) then having certain methods declared as throwing "expected" exceptions would be useful. Given the present architecture, however, it's better to simply declare most exceptions as being unchecked.

Related

Should I throw checked or unchecked exception for invalid input? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm writing a method which expect some input. Now, I thought that it would be a good practice to write it in a defensive way (i.e. checking that the input is correct).
Basically, the input should be okay since there's only one place (reliable) that uses this method.
So my question is,
Is the defensive programming justified here?
If so, should it throw a checked or unchecked exception?
Multiplying in an idiomatic way the same input checks in each layer of the call is generally a bad practice : you repeat yourself and changes for it can fast become an hell or a messy.
So I would think that if your method is designed to be an API usable by multiple client classes it should do this check even it may be redundant. Otherwise just stay DRY.
Note that the best way to ensure consistency in your API is covering your methods by unit tests.
In this way you provide the checks only when its functional requirement demands that and you don't overthink.
If so, should it throw a checked or unchecked exception?
Using checked or unchecked exceptions usage is very debatable.
In theory checked exceptions are great when it is required that the client handles it. But in practice it may become noise if the client don't want to handle it or if the method is used inside a lambda body.
Think about what will happen to the rest of the system or application if you did not have that check and some invalid input came in.
Do you have a safe default value to fallback and use? Is it the correct value for all cases? Does the caller/client of your code/API need to be notified of this?
So, based on this, you can even just log a warning and can continue using the default value. But in most cases, it will not be the case.
[..] there's only one place (reliable) that uses this method.
It is as of today. In the future, it might change. So, IMO, you can have the check that the input is valid.
should it throw a checked or unchecked exception?
That again takes us back to the callers or clients of your code/API. Do you want them to expect it to happen and handle it?
If they can handle the exception and recover, then it makes sense (Note: This means that all the callers need to have a try..catch block when calling your API/code). Else, if they are supposed to pass a valid value and if they don't, an unchecked exception will do (Make this clear in the contract/Javadoc)
Let us look at an example in the Java libraries itself.
Many methods in the File class throw a checked exception.
Integer.valueOf throws an NumberFormatException (which is an unchecked expcetion) if the input is invalid.
A good practice is, any public API must validate its inputs.
Also, have a look at Java: checked vs unchecked exception explanation
before deciding
Basically, the input should be okay since there's only one place
(reliable) that uses this method.
It's great, that you reason about your function this way. You just defined a contract for your function. It says, that this function expects a valid input. In this case, it is a very good practice to employ defensive programming by throwing an exception when invalid input is detected. This exception will greatly simplify detection of callers of your function, who broke contract and called your function with invalid input.
If you did not throw a dedicated exception, than (if you are lucky) your function might break by throwing a generic technical exception, e.g. NullPointerException or perhaps ArrayIndexOutOfBoundsException. Such stacktrace still shows, that something wrong happened, when your function was called. However, you need to analyze, "what" happened. In worst case, your function would not throw any exception at all and "somehow" process invalid input. Your program than can later break on seemingly unrelated location or in even worse case, it does not break and it presents wrong result to the user.
Is the defensive programming justified here?
Yes, it definitely is.
If so, should it throw a checked or unchecked exception?
Checked vs unchecked exceptions is still an ongoing debate. You can find many answers to this question on StackOverflow. Scala language only has unchecked exceptions. I personally prefer them too.
What if your function expects invalid input too?
Typically, these are functions, which receive input from humans. For example an user registration form requires password, which is not too short and contains at least one digit. In this case, "failure" is expected and should somehow be encoded in function's return value, so that caller of the function is forced to inspect both kinds of return value - Success and Failure. Such return values can be modeled using algebraic data types. Java does not allow to model ADTs naturally and we got used to model Failure by throwing an exception. Maybe in this case checked exceptions still make sense.
Edit:: Other answers go into more details on "when" to validate and when to not. To summarize: public methods - yes; do not repeat same validation across layers.
I didn't take your whole question into account, so I will change my answer.
Should you check input?
With public methods - Always. Reason being that best practice is always to call interfaces and not implementations. So when you have an interface, you want anyone using your implementation of it, to get proper feedback if they pass invalid arguments.
Should you throw exceptions?
Yes! As Uncle Bob says it's better to forget to catch an exception than forget to check a return value to check for errors. In other words, exceptions are more fool proof as they don't fail "silently".

Using exception classes to model errors

I want to know whether it would be right to use exception classes as regular classes to handle application errors (just regular controlled errors, not exceptional ones), without throwing them with the proper language clause (eg. instantiating them and returning them from a method). I've been discussing this topic recently with some colleges and I think that exceptions should only be used as exceptions, but I'd like to listen to more opinions.
What you mean by "controlled error" is actually known by the name checked exception.
"Exceptional exceptions" are known as unchecked exceptions.
The difference is explained here: Checked vs Unchecked exception
So, you see: Java comes with a built-in mechanism to distinguish between
exceptions caused by programming mistakes (e.g. NullPointerException when passing unexpected null as an argument) -- unchecked exceptions
versus anticipated exceptions that should be handled by the caller (e.g. IOException when some kind of I/O went wrong) -- checked exceptions
Returning instances of Exception (or any subclass) would be considered a misuse in virtually all circumstances.
You could ask your colleague how he/she would implement an exceptional outcome of a method with this signature:
public String createStringOrFailWithException();
Returning an Exception? Certainly not, because this requires a different return type.
Throwing the exception instead allows you to keep the return type, and to benefit from vast exception handling capabilities, including finally blocks and try-with-resources statements, to give only two examples that you don't want (should not) implement by yourself.
I suggest keeping Exceptions "exceptional". I.e. don't build them into your app logic. Use more meaningful things like a ActionXResponse class etc that could indicate failure, and even have an Exception as a property which the controller could check for "controlled exceptions". It's much more meaningful when you have your own class as a response.
Another guideline I'd suggest, along with keeping Exceptions "exceptional" is to avoid checked Exceptions (compile-time).

The role of runtime exceptions in defining a methods “contract” and expressing the intentions of an operation and a classes ADT

Could it be said that RuntimeException's may play a role in defining an operation, as part of the notion of a classes ADT and a particular operations "contract".
Since one chooses to include chosen runtime exceptions in the 'throws' list in a methods header (as well as a methods javadoc) - it is not forced by the compiler and is discretionary depending upon the exception - could this not be considered an effort to emphasize something about the intention of a methods "contract" and how it should be understood to work? Is this the case?
We recognize that some RuntimeExceptions's are simply thrown as "errors" for program logic that needs correcting during development and testing, whereas others could be considered to perform a similar role to that of checked exceptions. Here by embodying instances where a handleable and recoverable situation may occur - a client user should be able to take some reasonable action to allow the sw system to recover and respond appropriately. One designs an ADT and an operation to emphasize how it should be used. I wondered (considering the above) if we should consider as part of this:
"The conveying to the client developer of the need to handle certain Runtime Exception's that can sensibly be handled and anticipated"?
Do we consider the declaration of RuntimeException's in an operations header and documentation to be signalling such an intention and expectation by the code/ API developer to the client user?
Emphasizing the RuntimeExceptions it may throw by declaring them in a throws section (that one should thus handle) and or, declaring them in a javadoc (that one should instead potentially just be aware of) could perhaps be considered as part of this “contract” - that one should understand and uphold in defining and working with an interface (an operation). Therefore, by choosing to emphasize certain RuntimeExceptions (which are a choice), could this therefore be a part of the concept of "design by contract" that one shapes and expresses – it is about intention (what a method should provide as a service, but (pertinant here) - how the method is intended to be used by a client and his/ her expected responsibilities)?
Also, if/ or what, is the relationship between the throwing and documenting of Runtime Exceptions and the software design principle of design by contract is?
Another way of looking at my question i suppose is - One can catch a runtime exception if desired. I think the vast majority of cases where a runtime exception might occur and is thrown relate to situations that never or should never occur in correct client code. Most of these situations relate to incorrect logic or misuse of a method (and handling code would be excessively numerous and not sensible to include in these situations). However, in some less frequent cases, it is possible for some runtime exceptions to be situations that one could (and should) handle. This is why I think (I interpret I coud be wrong), the compiler doesn't require one to handle runtime exceptions - the compiler cannot tell the difference. It cannot distinguish. Checked exceptions are almost always sensibly handleable, but most runtime exceptions are likely not. The nature of a runtime error governs this. – Another angle on my question I suppose relates to the notion that the latter can sometimes be the case and are we supposed to consider this as part of the contract we emphasize as described above and the software design principle of "design by contract"?
Since neither the throws clause is required by the Compiler for subclasses of RuntimeException if you throw one in a method, nor is it required to catch them if you call such a method, it is just for documentation.

How should I return a value from function?

Three ways I see here:
1) make function return that value explicitly
2) add additional argument to the function's argument list and pass string holder as that parameter. After the function completes its execution, that string holder will contain the result of the function.
3) throw an exception from that function that will contain the result.
I for myself see first choice more preferable because it's simple, intuitive and straight.
On the other hand, when execution of the function goes in a wrong way there may be additional choices like throw an exception or use a variable passed through parameter to save errors if any happen.
Intuitively, I see that ideal choice is to have explicit return value and throws declaration. So return value is used for normal execution and caught exception will signal about abnormal situation. But I myself don't like exceptions too much if only it is not the completely unpredictable error, so I'd use explicit return value and additional parameter to hold some extra-situation logs or errors.
Please advise books or articles on the subject (it shouldn't necessary talk about Java, any other languages with similar mechanisms are also suitable).
You absolutely want option #1. Exceptions are not unpredictable; if you use them correctly, they are in fact entirely predictable. You can throw different exception types based on the error (FileNotFoundException, IllegalArgumentException, SomeConditionSpecificToMyAppException, etc), and those exceptions can contain any error or diagnostic information you need to convey.
Here's a good section in the Java SE tutorial on exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/
Java methods have return values for a reason: to return their results. In the vast majority of cases #1 should be your only choice. Even if you want to return a wrapper object e.g. because you need to return multiple values, you should probably just return the thing...
Exceptions are just that: they are thrown in exceptional (i.e. abnormal) circumstances. Since traditionally throwing an exception also implies a performance impact, exceptions should not be thrown during normal operation.
Why are you trying to confuse yourself?
EDIT:
On the other hand, exceptions are quite suitable for rare/abnormal conditions:
They have built-in support for the generation of debugging information. Getting a stack trace is half the battle in dealing with most bugs.
All decent debuggers allow for thrown exceptions to be used as a break point, which can be invaluable.
Exceptions allow for error conditions to be passed up the method call chain relatively transparently, allowing for the error handling code to be placed with as much granularity as desired.
Exceptions are the standard way to deal with error conditions in Java. This should be enough for most programmers. Please respect the people that will have to work with your code and don't break such basic conventions by reinventing the wheel...
I would use choice 1 almost every time. There is nothing stopping you throwing a Exception as required.
Please read Code Complete by Steve McConnell. It's all there.

In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]

This question already has answers here:
Closed 10 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
When to choose checked and unchecked exceptions
When should I create a checked exception, and when should I make a runtime exception?
For example, suppose I created the following class:
public class Account {
private float balance;
/* ... constructor, getter, and other fields and methods */
public void transferTo(Account other, float amount) {
if (amount > balance)
throw new NotEnoughBalanceException();
/* ... */
}
}
How should I create my NotEnoughBalanceException? Should it extend Exception or RuntimeException? Or should I just use IllegalArgumentException instead?
There's a LOT of disagreement on this topic. At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.
At my current job, I find that there are many who are for Runtime exceptions in many or all cases.
Here's what I think: Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller. With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it. Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.
From a philosophical point of view, a method call is a contract to some degree between the caller and the called. Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out. That is, return values or exceptions.
My experience tells me that I get higher quality, that is, code that JUST WORKS, when I'm using checked exceptions. Checked exceptions may clutter code, but there are techniques to deal with this. I like to translate exceptions when passing a layer boundary. For example, if I'm passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn't care that I'm persisting to a SQL database, but will want to know if something could not be persisted. Another technique I use is to create a simple hierarchy of exceptions. This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters.
In general, I think the advice by Joshua Bloch in Effective Java best summarises the answer to your question: Use checked expections for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition).
So in this case, if you really want to use exceptions, it should be a checked one. (Unless the documentation of transferTo() made it very clear that the method must not be called without checking for sufficient balance first by using some other Account method - but this would seem a bit awkward.)
But also note Items 59: Avoid unnecessary use of checked exceptions and 57: Use exceptions only for exceptional conditions. As others have pointed out, this case may not warrant an exception at all. Consider returning false (or perhaps a status object with details about what happened) if there is not enough credit.
When to use checked exceptions? Honestly? In my humble opinion... never. I think it's been about 6 years since I last created a checked exception.
You can't force someone to deal with an error. Arguably it makes code worse not better. I can't tell you the number of times I've come across code like this:
try {
...
} catch (IOException e) {
// do nothing
}
Whereas I have countless times written code like this:
try {
...
} catch (IOException e) {
throw new RuntimeExceptione(e);
}
Why? Because a condition (not necessarily IOException; that's just an example) wasn't recoverable but was forced down my throat anyway and I am often forced to make the choice between doing the above and polluting my API just to propagate a checked exception all the way to the top where it's (rightlfully) fatal and will be logged.
There's a reason Spring's DAO helper classes translate the checked SQLException into the unchecked DataAccessException.
If you have things like lack of write permissions to a disk, lack of disk space or other fatal conditions you want to be making as much noise as possible and the way to do this is with... unchecked exceptions (or even Errors).
Additionally, checked exceptions break encapsulation.
This idea that checked exceptions should be used for "recoverable" errors is really pie-in-the-sky wishful thinking.
Checked exceptions in Java were an experiment... a failed experiment. We should just cut our losses, admit we made a mistake and move on. IMHO .Net got it right by only having unchecked exceptions. Then again it had the second-adopter advantage of learning from Java's mistakes.
IMHO, it shouldn't be an exception at all. An exception, in my mind, should be used when exceptional things happen, and not as flow controls.
In your case, it isn't at all an exceptional status that someone tries to transfer more money than the balance allows. I figure these things happen very often in the real world. So you should program against these situations. An exception might be that your if-statement evaluates the balance good, but when the money is actually being subtracted from the account, the balance isn't good anymore, for some strange reason.
An exception might be that, just before calling transferTo(), you checked that the line was open to the bank. But inside the transferTo(), the code notices that the line isn't open any more, although, by all logic, it should be. THAT is an exception. If the line can't be opened, that's not an exception, that's a plausible situation.
IMHO recap: Exceptions == weird black magic.
being-constructive-edit:
So, not to be all too contradictive, the method itself might very well throw an exception. But the use of the method should be controlled: You first check the balance (outside of the transferTo() method), and if the balance is good, only then call transferTo(). If transferTo() notices that the balance, for some odd reason, isn't good anymore, you throw the exception, which you diligently catch.
In that case, you have all your ducks in a row, and know that there's nothing more you can do (because what was true became false, as if by itself), other than log the exception, send a notification to someone, and tell the customer politely that someone didn't sacrifice their virgins properly during the last full moon, and the problem will be fixed at the first possible moment.
less-enterprisey-suggestion-edit:
If you are doing this for your own pleasure (and the case seems to be this, see comments), I'd suggest returning a boolean instead. The usage would be something like this:
// ...
boolean success = transferTo(otherAccount, ONE_MILLION_DOLLARS_EXCLAMATION);
if (!success) {
UI.showMessage("Aww shucks. You're not that rich");
return; // or something...
} else {
profit();
}
// ...
My rule is
if statements for business logic errors (like your code)
cheched exceptions for environment errors where the application can recover
uncheched exception for environment errors where there is no recovery
Example for checked exception: Network is down for an application that can work offline
Example for uncheched exception: Database is down on a CRUD web application.
There is much documentation on the subject. You can find a lot by browsing the Hibernate
web pages since they changed all exceptions of Hibernate 2.x from checked to unchecked in version 3.x
I recently had a problem with exceptions, code threw NullPointerException and I had no idea why, after some investigation it turned out that real exception was swallowed(it was in new code, so its still being done) and method just returned null. If you do checked exceptions you must understand that bad programmers will just try catch it and ignore exception.
My feeling is that the checked exception is a useful contract that should be used sparingly. The classic example of where I think a checked exception is a good idea is an InterruptedException. My feeling is that I do want to be able to stop a thread / process when I want it to stop, regardless of how long someone has specified to Thread.sleep().
So, trying to answer your specific question, is this something that you absolutely want to make sure that everyone deals with? To my mind, a situation where an Account doesn't have enough money is a serious enough problem that you have to deal with it.
In response to Peter's comment: here's an example using InterruptedException as concrete case of an exception that should be handled and you need to have a useful default handler. Here is what I strongly recommend, certainly at my real job. You should at least do this:
catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
That handler will ensure that the code catches the checked exception and does exactly what you want: get this thread to stop. Admittedly, if there's another exception handler / eater upstream, it's not impossible that it will handle the exception less well. Even so, FindBugs can help you find those.
Now, reality sets in: you can't necessarily force everyone who writes an exception handler for your checked exception to handle it well. That said, at least you'll be able to "Find Usages" and know where it is used and give some advice.
Short form: you're inflicting a load the users of your method if you use a checked exception. Make sure that there's a good reason for it, recommend a correct handling method and document all this extensively.
From 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.
Note that an unchecked exception is one derived from RuntimeException and a checked exception is one derived from Exception.
Why throw a RuntimeException if a client cannot do anything to recover from the exception? The article explains:
Runtime exceptions represent problems
that are the result of a programming
problem, and as such, the API client
code cannot reasonably be expected to
recover from them or to handle them in
any way. Such problems include
arithmetic exceptions, such as
dividing by zero; pointer exceptions,
such as trying to access an object
through a null reference; and indexing
exceptions, such as attempting to
access an array element through an
index that is too large or too small.
A checked exception means that clients of your class are forced to deal with it by the compiler. Their code cannot compile unless they add a try/catch block.
The designers of C# have decided that unchecked exceptions are preferred.
Or you can follow the C-style and check return values and not throw exceptions.
Exceptions do have a cost, so they shouldn't be used for control flow, as noted earlier. But the one thing they have going for them is that they can't be ignored.
If you decide that in this case to eschew exceptions, you run the risk that a client of your class will ignore the return value or fail to check the balance before trying to transfer.
I'd recommend an unchecked exception, and I'd give it a descriptive name like InsufficientFundsException to make it quite clear what was going on.
Simply put, use checked exception only as part of external contract for a library, and only if the client wants/needs to catch it. Remember, when using checked exception you are forcing yourself on the caller. With runtime exception, if they are well-documented, you are giving the caller a choice.
It is a known problem that checked exceptions are over-used in Java, but it doesn't mean that they are all bad. That's why it is such in integral part of the Spring philosophy, for example (http://www.springsource.org/about)
The advantage of checked exceptions is that the compiler forces the developer to deal with them earlier. The disadvantage, in my mind anyway, is that developers tend to be lazy and impatient, and stub out the exception-handling code with the intention of coming back and fixing it later. Which, of course, rarely happens.
Bruce Eckel, author of Thinking in Java, has a nice essay on this topic.
I don't think the scenario (insufficient funds) warrants throwing an Exception --- it's simply not exceptional enough, and should be handled by the normal control flow of the program. However, if I really had to throw an exception, I would choose a checked exception, by extending Exception, not RuntimeException which is unchecked. This forces me to handle the exception explicitly (I need to declare it to be thrown, or catch it somewhere).
IllegalArgumentException is a subclass of RuntimeException, which makes it an unchecked exception. I would only consider throwing this if the caller has some convenient way of determining whether or not the method arguments are legal. In your particular code, it's not clear if the caller has access to balance, or whether the whole "check balance and transfer funds" is an atomic operation (if it isn't then the caller really has no convenient way of validating the arguments).
EDIT: Clarified my position on throwing IllegalArgumentException.
Line is not always clear, but for me usually RuntimeException = programming errors, checked exceptions = external errors. This is very rough categorization though. Like others say, checked exceptions force you to handle, or at least think for a very tiny fraction of time, about it.
Myself, I prefer using checked exceptions as I can.
If you are an API Developer (back-end developer), use checked exceptions, otherwise, use Runtime exceptions.
Also note that, using Runtime exceptions in some situations is to be considered a big mistake, for example if you are to throw runtime exceptions from your session beans (see : http://m-hewedy.blogspot.com/2010/01/avoid-throwing-runtimeexception-from.html for more info about the problem from using Runtime excpetions in session beans).

Categories