What exception should I throw - java

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

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.

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.

Related

Transforming Exceptions thrown from an external library in a centralized way

I would like to ask a code style question around Java Exceptions. I am using Java to call a C/C++ library using JNI. The convention in the library I am using is that most of the methods I can call will throw the same exception type for all errors. Let's call that a LibException. Now LibException is really a wrapper exception for a multitude of errors that can come up ranging from authentication problems, connection problems or more serious problems like corrupt input etc. LibException also contains an error code int as well as the error description string.
Even more confusingly LibException can also wrap one of my own exceptions if I throw it at the library in a callback! What I mean by that is that I sometimes provide a callback method, it is called by the library and I sometimes have to throw an exception in the callback. In that case the library picks up the exception, wraps it up in a LibException and throws it back at me in the original method call.
I would like each of the underlying problem to be handled differently. Authentication problems need to be shown to the user so he can retry, users should be notified of connection problems, but more serious problems may have to trigger my diagnostics report system (an automated mechanism that can send me parts of the logfile for debugging) and of course any exceptions I throw towards the library in the callback need to be rethrown as the original exception type.
Since I am calling different methods at multiple locations, I thought it would be a good idea to put some structure around the exception handling of LibExceptions. This is to avoid code repetition but most importantly to make sure that the different exception types are handled properly and that future me does not forget to, for example, notify the user that authentication failed.
I have tried a bunch of approaches but I am not entirely happy with the code structure I get so I would like some ideas on best practices from the community.
Static method that includes logic to sort the exceptions and throw a bunch of other exceptions
public static void handleException(LibException e) throws AuthenticationException, ConnectionException, SeriousException, MyException (MyException would be my exception that I throw in the callback)
+ve This works well in that it forces the handling of all the thrown exceptions.
+ve If a new exception type is added, the compiler would force me to handle the new exception
-ve Even though handleException() is a method that always throws an exception, the compiler (rightly) does not know this. This means that if we use handleException() in a method that has to return something, the compiler complains that a return type was missed. To make the compiler happy I have to throw another exception right after calling handleException() so the compiler understands that it will not be getting a return value because an exception is definitely thrown.
-ve I don't like the line that looks like Handler.handleException(libEx) since it's not entirely obvious that it throws a bunch of exceptions.
-ve Hard to customize the exception messages with context from the location the exception occurred (i.e. which URL we could not connect to).
A method that returns an enum with the different types of exceptions that I defined. Based on the enum I can then create the different exceptions to throw.
public static ExceptionTypeEnum Handler.
+ve Since I create the exceptions, I can now customize some error messages with extra context
-ve I could still forget to handle an enum (especially if I create a new category in the future)
-ve I still need a bunch of custom code to create the exceptions at every place I catch a LibException
Similar to #2 but instead of an enum return I could have multiple methods such as isAuthenticationException(libEx) or isConnectionProblem(libEx) and then accordingly throw the exceptions myself.
-ve I would definitely forget to handle all sections properly especially if a new exception type is added later.
The exception handler could return an exception to throw up. But since we throw a number of different exceptions the getException() method would have to return the Exception base class. This means that exception handlers would have to have prior knowledge of what exceptions could be thrown and also catch the Exception class making my exception handling more difficult.
Now in case I confused everyone with this question, I guess what I am trying to find an elegant solution to is similar to the problem described on section 'Checked exceptions inappropriately expose the implementation details' on page http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html
Does the community have any other suggestions of a coding method to properly and elegantly handle these LibExceptions?

How does one decide to create a checked excpetion or an unchecked exception [duplicate]

This question already has answers here:
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 6 years ago.
I want to know how does one know to create and throw a checked exception or an unchecked exception.
For example I have a service which takes some data and validates it before using it. During validation a certain field did not meet the rules and I want to throw an exception say ValidationException(). How will I know of decide it should be checked or unchecked.
In another case I am calling an external web service from my code for example the google stock api. Let's assume i have a timeout of 3 seconds. If the time exprires i want to throw an exception say BackendException(). How will I know if it should be a checked exception or an unchecked exception.
Thanks in advance.
There might be different opinions but I'd say the difference is how the caller should handle that exception:
If you want to make sure the caller handles the exception either by doing something (logging, trying to recover etc.) or rethrowing then use a checked exception. An example would be said ValidationException: if the data is invalid the caller should have to handle that, e.g. by telling someone to fix the data or by trying something else. (Note that there may be unchecked validation exceptions such as javax.validation.ValidationException. There can be various reasons for making those unchecked, e.g. if a framework doesn't allow/support checked exceptions or if some central handler will catch them anyway so the developer doesn't have to bother.)
It you don't want to force the caller to handle exceptions that normally should not be thrown (e.g. programming errors etc.) use an unchecked exception. An example for this might be the always dreaded NullPointerException: it should not happen that something you want to use is null so it might be considered a programming error. If something could be null but should not you might want use a checked exception instead.
Note that some libraries/methods use IllegalArgumentException which is an unchecked exception. If this exception is thrown there's normally a programming error in that the contract of a method (e.g. the parameter value must not be negative) is violated and that the caller should fix the code or do some checks himself.
Another point of view might be: is the exception expected to be thrown in some cases or not? Expected exceptions (that still mean some kind of error happened) would be checked exceptions since that way you'd communicate to the caller that he should expect those exceptions being thrown in some cases (e.g. if the data is invalid). If the exception is unexpected you should not force the caller to handle such an exception since you'd not expect it to be thrown at all - thus it would be an unchecked exception.
As per Joshua Bloch, Book Effective Java, Item 58 summarizing it in a single line. Thumb rule is Use checked exceptions for recoverable conditions and runtime exceptions for programming errors.

Should I put throws IllegalArgumentException at the function?

I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException class as it seemed right name for the issue, but should I put the throws IllegalArgumentException at the function definition ?
I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.
RuntimeExceptions like IllegalArgumentException are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.
Potential RuntimeExceptions should be documented somehow in the function contract (i.e. javadoc), either with the explicit #throws, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.
If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.
There's two types of exceptions:
runtime exceptions (like IllegalArgumentException and NullPointerException for example) don't need to be explicitly caught, because they 'shouldn't happen'. When they do, of course, you need to handle them somewhere.
regular exceptions NEED to be caught or declared to be thrown because they represent a more intrinsically difficult kind of error.
You need to read up on Unchecked Exceptions - exceptions which inherit from RuntimeException. They don't need to be declared in the method header.
http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
The last paragraph sums it up:
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.
IllegalArgumentException (along with some others, for example NullPointerException) are examples of a RuntimeException. This type of exception is not what's known as a checked exception. Java requires that methods declare which checked exceptions they throw and that if a called method might throw a checked exception, the calling method should either declare that it throws the exception itself, or catch and handle it.
As such, my concrete recommendation would be no, don't declare it. Certainly, though, you don't want to be catching it. In most cases, you also don't want to be throwing it unless this is unexpected behaviour. If it's quite normal and reasonable for the the method to be getting a value it doesn't like, an Exception is the wrong way to handle it.
You might also want to consider making use of assertions.
the first point when understanding exceptions is that they are for exceptional situations. While thinking about your method you must ask: "Should this method throws an exception if an exceptional value is passed through?" If the answer is "yes", put it in your method declaration.
I don't know if you get the idea, but it's kind of simple. It's just a matter of practice.

If catching null pointer exception is not a good practice, is catching exception a good one?

I have heard that catching NullPointerException is a bad practice, and i think it is sensibly so. Letting the NullPointerException to propagate to the top would allow the detection of a something going wrong. But many times I have seen many of my friends catching Exception directly so that they need not bother about all the different kinds of exceptions that might occur in the above code. Is this a good practice? What are the other kinds of exceptions that are best left unhandled? And besides it also makes sense to me to handle NullPointerException over a specific code where we are sure of the source of the exception. So when are exceptions to be handled and when should they not be handled? And what would be the possible list of exception that are best left unhandled?
Pokemon exception-handling is bad. Especially, if it's an empty block and you're simply swallowing them. You have specifically-typed exceptions for the reason that they actually mean specific things in specific contexts (essentially they're telling you what went wrong). So by catching Exception you're saying that you don't care what those exceptions are and that you don't care what happened. This is probably not what you want.
In general, when catching exceptions follow these rules:
Does it make sense to handle the exception at this level? If yes, then handle it. If not, then propagate.
In conjunction with the first rule, "handling" can also mean, catching, wrapping, and re-throwing. This is a way of preventing abstraction-leakage so that callers of your method don't have to know about the underlying implementation.
An empty catch block doesn't mean that you've handled the exception. That's called "swallowing"; at the very least, you want to log the exception. Sometimes an exception happening is actually part of the logical flow of your code, and so you might want to do something special (but this is, pardon the pun, the exception rather than the rule. It is better to check for situations that cause exceptions rather than incorporating them into the logical flow of your code).
You can easily check for a null value in your code, so there is no need to explicitly catch a null-pointer exception. It doesn't make sense to let a NullPointerException happen (and it's bad practice). Even if you have some code that throws a NullPointerException, and it is code that you do not control and cannot fix, you should determine the input parameters that cause the NullPointerException and specifically test for them.
Another exception that you shouldn't catch is the IllegalArgumentException. This exception means that you've passed in an argument that does not make sense. Instead of catching this exception, you should explicitly test your input parameters to ensure that they are sane and that they cannot cause an IllegalArgumentException.
The 'reason' that catching NullPointerException is considered a bad practice is not because you're supposed to let it bubble up when something goes wrong! Saying any exception is 'best left unhandled' based solely on its type seems like a bad idea.
A NPE is considered the result of a programming error. A strictly correct program should never generate one. The reason seeing it caught is bad is it usually means that the code threw one, and the programmer decided to just catch it and cover it up, rather than fix the broken code that caused it in the first place!
If, for example, you were coupled for business reasons to an API that has a bug inside and occassionally throws a null pointer, it would be perfectly legitimate to catch it, do something about it/inform the user with a better message. Letting 'null' hit the UI just because someone said "Catching Null Pointer Exception is bad" would make no sense!
Catching java.lang.Exception can be legitimate in specific cases, but generally "I'm lazy" is not one of them. :) For example if you're implementing an API and want to make absolutely sure no exception ever comes out of it that isn't in the specification, you might catch Exception and wrap it in some application exception you've defined.
You should only catch an Exception if you can add some value by doing so. Otherwise you should let it pass to the caller.
NullPointerException is usually the result of a bug in your code. How can you sensibly fix this in a catch block?
Not being bothered about Exceptions is not good practice.
In general, the only times you should catch an exception is if you can handle it in some meaningful way. If you can't you should simply let it bubble to the top and terminate the process. For instance, could you recover in some meaningful way from a NullPointerException or I/O error? I think not.
My rules for exception handling:
In general, don't catch exceptions, unless you can handle them in some meaningful way.
Catch exceptions at process/machine boundaries, log the caught exception along with any context available to you and re-throw it. If the exception is a custom exception, you may wrap it in an exception of a type known/useful to the invoking process and throw that.
You may also catch exceptions at a low level, where you have the most runtime context available, log the exception and associated context, then rethrow the exception.
When rethrowing, use throw ; rather than throw caughtException ;. Use of the former syntax preserves the original stack trace; use of the latter syntax creates a new stack trace, beginning with throw caughtException ; -- you lose all the context and call stack up to the point at which the exception was caught.
You may, if you so choose, catch exceptions at a high level and gracefully terminate the process, logging the exception information so as to help debug and correct the underlying problem.
Do not use exceptions as a flow control mechanism (if possible). Exceptions are supposed to be, well, exceptional in nature. Rather, premptively, enforce the caller's end of the contract (preconditions) for any methods you are invoking.
See Bertrand Meyers' book , Object Oriented Software Construction, 2nd ed. for more information.
The main rule about catching exception is that you have to know why you are doing this. Exception class is caught in cases when programmer wants to do generic error processing and he does not really care what exactly happened, the main thing is just something went wrong. In that case he may decide to rollback transaction or do some cleanup.
If you are catching specific exception try to apply the same rule. I you know exactly why you are doing that, then it's to do that. But it's very rare case when someone would want to do something really special in case of NPE.
if you have a graceful way to handle your exception it is useful to catch it, if not hope that the caller has a nice way to handle it.

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