When is it suitable to throw an Exception? - java

I've seen some code recently where the author was throwing exceptions for almost every constructor and throwing runtime exceptions for things like the code below, in a method that returns int:
if(condition){
return 1;
}
if(condition){
return 2;
}
if(condition){
return 3;
}
throw new RuntimeException("Unreachable code");
// method ends here
I wouldn't have personally thrown an exception there, because I would have structured it using if and else if statements, and in this particular case your code would be fundamentally wrong for it not to satisfy one of the conditions anyway.
There are plenty of places you could throw runtime exceptions, that would never be reached if you're code is working correctly, sometimes it just seems like the author doesn't trust the code to work, in the case of the code block above. Also, every constructor could throw an exception for if it doesn't initialize correctly, but you could also structure it so that the object would be null - which you could then check for in main, for instance.
What I'm asking, basically, is when is it worth throwing an exception?

The point of exceptions is to communicate exceptional situations.
In that sense: if it is absolutely unexpected that all your conditions are false in your example, and that there is also no valid return value to indicate that situation, then throwing that RuntimeException is the reasonable thing to do here; but I would probably change the message to:
throw new RuntimeException("All conditions failed: " + some data)
As said: it is about communicating; in this case to the person debugging the problem. So it might be helpful here to include the information that is required to understand why exactly all those checks turned out false.
The point is: there is a contract for that method; and that contract should include such details. Meaning: if that method is public, you should probably add a #throws RuntimeException with a clear description.
And it is also a valid practice to use RuntimeException for such situations; as you do not want to pollute your method signatures with checked exceptions all over the place.
Edit: of course, balancing is required. Example: my classes often look like:
public class Whatever {
private final Foo theFoo;
public Whatever(Foo theFoo) {
Objects.requireNonNull(theFoo, "theFoo must not be null");
this.theFoo = theFoo;
So, there might be a NPE thrown from my constructors; yes. But: only there. All my methods can rely on the fact that all fields were initialized to non-null; and they are final, so they will always be non-null.
Meaning: one has to stay reasonable; and "develop" a feeling for: which problems are exceptional but possible; and which ones are so impossible that you don't pollute your code all over the place to check for them.
Finally; just to make that clear - adding exceptions is only one part of the equation. When something throws, then you need something to catch! Therefore, as said: balancing comes in. Whatever you do in your code has to "add value" to it. If your code doesn't fulfill a clear, defined purpose, then chances are: you don't need it!

GhostCat has basically covered all that need to be said when and why we should use exceptions. Just to take it further, the best thing to do is to weigh the cost benefit of including an exception. The cost in this context refers to performance as well as degraded client friendliness of the application while the benefit is the smooth running of the application as well as being user-friendly. In my opinion first one should distinguish between application and system error. Then these errors further need to be scrutinised after dichotomizing them into compile and runtime ( note that compile time errors normally do not need to be handled with exception but to debug and find out issues you need to handle them using debug tools such as assert of C++). Even if the nitty-gritty of inclusion of exception handlers depends on the context of the specific application, generally, one can postulate the following principles as a starting point:
1- Identify critical hotspot crash points of the code;
2- Distinguish between system and application errors;
3-Identify run time and compile time errors;
4- Handle compile time error using debugging tools such as assert or preprocessor directives. Also, include exception handlers or trace or debug to handle runtime errors
4-weigh the consequences of handling exceptions at run time;
5- Then provide a testable framework, which normally can be handled during Unit Test, to identify where exceptions need to be included or not.
6- Finally, decide where you need to include the exception handlers for your production code taking into account factors you think are decisive and need to include exception handler to handle them.
7- Finally finally .... you need to have a crash proof exception handler that should be triggered in the unlikely scenario that the application crashes and include fallback safety to handle states to make the application very user-friendly.

Related

When is the right time to throw a RuntimeException?

I'm developing a library for Android, which I intend to open source and naturally I want to tick all of the boxes before I publish it - so users are suitably impressed with my code. Ahem.
As with many libraries, there are certain basic configurations necessary in order for the library to function.
public static final String API_KEY = "your_api_key_here";
In the above instance, when a user passes their API key to the library, I'm putting a simple string match in for "your_api_key_here" and if it matches, I'm going to throw a RuntimeException, as they quite simply haven't read the basic instructions and I want their app to die.
Is this a valid use of a RuntimeException? If it isn't, then in Java what is?
EDIT - My motivation for posting this is due to this post, where the OP is lynched by shouts of "why!?" for asking how to throw one.
ANSWER - In this instance, it seems to be more a matter of preference than right or wrong either way - at least no one has so far objected. This scenario should only occur during the testing phase for a developer and never in production. If this wasn't the case, I wouldn't have chosen an uncaught exception.
I've marked an answer as correct due to the most upvotes and following #mech's comment below, I have created a custom ReadTheDocumentationException which provides a suitably persuasive message.
I think you should use illegal argument exception which is subclass of java.lang.RuntimeException . You can do something like this
if(API_KEY.equals("your_api_key_here"))
throw new IllegalArgumentException("you message here");
For more info see this
You should create your own exception by extending RuntimeException or any other Exception. IllegalStateException would work for a case when someone terribly misbehave.
It sounds like part of your question deals with what is the proper use of RuntimeException, and partly deals with how your library should behave if misconfigured. I'll deal with mostly the former.
In Java, there are two types of exceptions, checked and unchecked.
RuntimeException and all of its subclasses are "unchecked" exceptions, meaning there is no requirement from the compiler to catch them. You can use these to crash your process if something is very wrong. The caller can still catch and handle them on their own, so be prepared that the caller may continue to call into your lib incorrectly.
Exception and all of its subclasses (except RuntimeException) are "checked", meaning that the compiler requires the caller to catch them or declare in a method declaration that it could be thrown. You use this in cases where you expect the caller to try to recover from whatever condition caused the exception to be thrown.
In your case, you can throw a RuntimeException with a meaningful message, or a custom subclass of RuntimeException with a message to indicate to the caller exactly what went wrong and how to remedy it. It doesn't really matter what you choose, but many people choose to subclass for clarity. I'd just make sure that the exception is never thrown by surprise in order to have clear rules for engagement for your lib.

Making a checked exception a RuntimeException

I'm working on a legacy system that has a custom exception that's used gosh-frickity-everywhere. It was inspired by the ServletException class, that said "well any time you have an exception in your Servlet, you'll want to throw this ServletException".
As the system evolved (over 10 years) a more robust system of catching the exceptions at a higher level has taken place and it's no longer necessary to wrap every exception in this custom exception. (One could argue it never was, but that's another story. It's a stable app, so I tend not to complain too much!!) But we're not going to be refactoring them all at once, just slowly over time.
However, one thing that would make things simpler going forward would be if the custom exception were a runtime exception instead of a checked exception. This way we wouldn't need to explicitly catch it everywhere, and legacy code that hasn't been refactored yet will just continue to throw this the same way as they'd throw a null pointer exception if one occurred.
My question is... What are the side effects of taking a once checked exception and making it a runtime exception?
I can't think of any, aside from warnings for unnecessary check and throws declarations, but it would be nice to get input from someone who has been down this road before.
Changing a checked exception into an unchecked one has very little practical effect on existing, working code, but you do need to watch out for the possibility that somewhere in your code you catch (RuntimeException ...). Such catches do not intercept your custom exception now, but they would do if you make it unchecked.
You might also run into issues if you do anything reflective related to methods that throw that exception (which apparently is most of them).
Something like that happened on an old module of a app that I had to maintain. The only problem translating exceptions to runtime is that you may lose granularity but that is entirely up to you to handle.
For example, we had a ton of code like this in the deeper layers:
catch(IOException e){
Throwables.propagate(e);
}
We used that pattern carelessly all over that layer and, when we needed to check the exception cause, we always had to get the cause of the exception and that made a lot of boilerplate in higher layers. To this day I believe it's better to create a good class hierarchy of non-checked exceptions in order to preserve granularity. e.g.
catch(IOException e){
throw new FileNotCreatedException(e);
}
And with this you can catch the exception easily in other layers and divide errors and fallbacks easily:
catch(FileNotCreatedException e){
notifyError(e);
} catch(NoMoreStorageException e){
releaseSomeStorage();
retryOperation();
}
Here are a few that I can think of
Runtime exceptions could potentially go to a layer where you didnot intend it to go.
ex: a Servlet ---> Service ---> DAO. Runtime exceptions thrown by DAO related to database interactions could potentially land up on Servlet. Clear segregation of layers where each layer handles all exceptions (checked/runtime) at its entry points can ensure that this doesn't happen.
Runtime exceptions can leave system in an inconsistent state.
ex: If the sequence diagram looks like Class A --> Class B ---> Class C and if Class B1 is injected between B and C therefore Class A ---> Class B ---> Class B1 ---> Class C then neither Class A, B, B1 would know that they might have to cleanup when this runtime exception occurs in Class C. In fact this can potentially affect the semantics of any dependency injection.
As a general thumb rule in my opinion:
Use checked exceptions when you "expect" the exception as part of a normal control flow and know how to handle it. ex: Validation of a business rule say account balance has to be greater than debit amount by atleast 100.
Use unchecked exceptions when you "don't expect" the exception as part of a normal control flow hence have no means of handling it yet you know that "some class" within your "layer" would handle it to ensure graceful degradation ex: DB connection lost would have handled by your "service" layer entry class.
Never use error. Only JRE has reasons to throw errors.

Always try-catch-finally for exceptions? Central error management?

I wonder if I always have to use try-catch-error blocks that clutter the code a lot, if I want to catch an error.
Or can I somehow define a global error catcher?
Especially regarding Java EE Webapps.
For every unhandled ex I'd like to log to a specific file, and display a general error page to the user.
I thought I might achieve that with aspects. But for aspects to catch on #AfterThrowing, I too have to introduce try-catch blocks. And as there is no central class for the backing-facades, I would have to surround every backing method with trycatches.
Then the aspect would take them, but I need something to catch without explicit throws exceptions.
How could I to that?
You are looking for the declare soft construct. This will wrap the given exception in a SoftException (an AspectJ-specific RuntimeException) so that it does not need to be explicitly handled. Then you can handle all of these exceptions with some AfterThrowing advice.
declare soft only exists in code style AspectJ (ie- there is no annotation for this). So, you will need to compile your code using the AspectJ compiler, but you can still use load-time weaving for this if you like.
See here:
http://www.eclipse.org/aspectj/doc/released/progguide/quick-other.html
And here:
http://www.eclipse.org/aspectj/doc/released/adk15notebook/declare-soft.html
Here's a code snippet that shows how it can be done:
aspect ErrorHandler {
declare soft : Exception : within(*);
after() throwing(Exception e) : handler(e) {
// do something...
}
}
This will route all exceptions in your system through your custom error handler. And you won't need to explicitly catch or throw them.
It's simple and powerful. Perhaps too powerful, though. I'd recommend refining and being more precise about exactly which exceptions should be softened and which ones need to be advised, but this is the basic idea.
You don't have to do this in every method.
You should not catch an exception that you can't "handle". Handling means more than just rethrowing or logging or printing a stack trace. I think handling means implementing a meaningful recovery strategy.
It might mean "the buck stops here": You're Gandalf on the bridge at the edge of a layer boundary, and no exception shall pass. You don't want users to see nasty messages, so you catch and route them to a friend, easy to understand page that tells them what to do next.
Finally isn't always necessary, but it's perfect for cleaning up resources like file handles and database cursors.
If you cannot handle an exception, there's no shame in adding the throws clause to the method signature and letting callers figure out what they want to do.
In the general case, there is no mechanism to do this - Java does not have what you're looking for.
However, depending on your circumstances, it might be possible.
web.xml Exception Handler
The web.xml file allows you to define a URL to be used to handle specified exception type. (See, for example, http://wiki.metawerx.net/wiki/Web.xml.ExceptionType).
Since you're writing a webapp, you may be able to just let the exceptions throw all the way to the top, and then handle them this way.
Custom interceptor
You mention that you have backing-facades. Depending on how they're being constructed, you may be able to put a generic proxy in front of them to catch and handle the exceptions you're interested in. You've tagged your question with spring, to you might want to look at Spring AOP Proxies.
There might be other ways to get what you want, but it will depend on the specifics of your application's architecture.
The finer control you have of the exceptions, the easier it will be to debug/provide a meaningful message.
To which extent? I would link that to the complexity / expected lifetime of your application. The bigger those are, the finer should be your handling.
I see two main approachs:
User approach: You get at least one exception handling for each UI action (so you can say: "Do not push that button AGAIN").
Debugger approach: Every method has its control.
Keep in mind that most handling could be just logging of rethrowing of the exception.
More to the point, most probably, your Java EE framework will have log options in its configuration files (many of them working with java.util.loggin or log4j). You could tweak that; of course, what is send to each log category will depend of the framework implementation (so maybe not all ERROR messages will be Exceptions).

Java - where and how should exceptions be used?

I was reading some things about exception handling in Java, to be able to write better code. OK, I admit, I am guilty; I've used too much try-catch{} blocks, I've used ex.printStackTrace() in the catch, not even using a proper logger (actually the System.out and System.err were redirected to a PrintWriter, so a log was generated). However, after a few hours of readings, I find myself in a strange place: the unknown. If the exceptions are designed to pass info about abnormal states of flow, how does one know WHERE is the proper level to do something with that info?
For instance, when a database error occurs, should one return a null value or an error code, or throw the exception? If thrown, WHERE should that exception be handled? I understand that is no use even to log an exception if you cant do anything about it. However, in GUI apps, that could easily kill your GUI (I am using SWT and I've seen this too often), even for the case of the menuShown() method (an ArrayIndexOutOfBounds exception will close the app, if not handled). The example could go on forever, but here's the summary of questions:
Does using try-catch() excessively have a negative impact on performance?
Is it better to use specific exception types? What if I missed catching one
of the possible X types of exceptions that could occur?
Frankly, I've heard of and use a mere 10% I think of the Java standard exceptions, in 2-3 years. Yes, someone said that if the caller don't know how to deal with the thrown exceptions, he SHOULD NOT HAVE THE RIGHT to call the throwing method. Is that right?
I've read this article of Anders
Hejlsberg, saying that checked exceptions are bad. Should that indicate that convenient exception swallowing is advised in some cases?
A picture is worth 1000 words; I guess some examples will help a lot
here.
I know the subject is eternal, but actually I am looking forward to review a middle-size project of 150 classes, using your advice. Many thanks.
The general rule of thumb for exception is, if you can do something about it, catch it and handle it, if you can't, re-throw it to the next method. To get into some of your specifics:
No, using excessive try/catch will not have a performance impact
Using the most specific type of exception you can. For example, you shouldn't generally throw Exception if you can avoid it. By throwing a specific type, you are letting the user know what can go wrong. However, you can rethrow it as something more generic so callers that are not concerned with the specific exception don't need to know about it (for example, a GUI won't care if it's an IOException vs an ArrayIndexOutOFBoundsException).
You will find people that like checked exceptions more and you will find people that like unchecked more. In general, I try to use unchecked exceptions because there is generally not a lot you can do about most checked exceptions, and you can still handle unchecked exceptions, you just don't have to. I frequently find myself rethrowing checked exceptions since I can't do much about them (another strategy is to catch a checked exception and rethrow it as an unchecked so classes higher in the chain don't need to catch it if they don't want).
I generally like to log exceptions at the point of where they are caught - even if I can't do anything about it, it helps to diagnose the problem. If you are not familiar with it, also look into the method Thread.setDefaultUncaughtExceptionHandler. This allows you to handle exceptions that are not caught by anyone and do something with it. This is particularly useful with a GUI app since the exception might otherwise not be seen.
To get into some examples:
try {
// some database operation
}
catch (IOException ex) {
// retry the database operation. then if an IO exception occurs rethrow it. this shows an example doing something other than just catch, logging and/or rethrowing.
}
I'll be happy to expand on any parts of this if you'd like.
Many good answers, let me just add a couple of points that haven't been mentioned.
Your exception types should be as specific as a caller is likely to distinguish them. By that I mean, if there are two possible errors, A and B, and any caller is likely to do exactly the same thing in both cases, then make a single exception class. If a caller is likely to do two different things, then make two exception classes.
For many, probably most, of the exceptions that I create, the only thing the program can realistically do is display an error message and give the user the opportunity to change his inputs and try again. Most validation errors -- invalid date format, non-digits in a numeric field, etc --fall into this category. For these I create a single exception type, which I usually call "BadInputException" or "ValidationException", and I use that same exception class throughout the system. When there's an error, I 'throw new BadInputException("Amount must contain only digits")' or some such, and then have the caller display it and let the user retry.
On the other hand, if the caller is reasonably likely to do different things in different cases, make them different exceptions.
Easy rule of thumb: If you have two or more exceptions that are ALWAYS handled with identical, duplicate code, combine them into a single exception. If your catch block is doing additional checking to figure out what kind of error this really is, it should have been two (or more) exception classes. I've seen code that does exception.getMessage and then looks for keywords in the message to figure out what the problem was. This is ugly. Make multiple exceptions and do it cleanly.
There are three good reasons to use exceptions rather than other ways of handling errors.
(a) It avoids the problem of "magic" return values, like non-null string is a real answer but null means there was an error. Or worse, "NF" means file not found, "NV" means invalid format, and anything else is the real answer. With exceptions, an exception is an exception and a return value is a return value.
(b) Exceptions neatly skip the main line of code. Usually when there's an error you want to skip a whole bunch of processing that does not make sense without valid data, and go right to displaying an error message and quitting, or retrying the operation, or whatever is appropriate. In the bad old dies we would write "GOTO panic-abort". GOTOs are dangerous for all the reasons that have been much discussed. Exceptions eliminate what was perhaps the last remaining good reason to use a GOTO.
(c) Perhaps a corrollary to (b), you can handle the problem at the appropriate level. Sometimes when an error happens you want to retry the exact same function -- like an I/O error might represent a transient communications glitch. At the other extreme, you could be ten levels deep in subroutines when you get an error that cannot be handled in any way but bombing out of the entire program and displaying a "sorry, armageddon has occurred, everybody in here is dead" message. With exceptions it's not only easy to choose the correct level, but you can make different choices in different modules.
Exception is there so the programmer of a Task does not have to deal with the problem by himself. (1): In case the problem is NOT LOGICAL to him to handle in the Task.
A task to read a String from a stream should not handle disk error isn't it. But it should be very logical to handle if data does not contain a String.
(2): He can't handle it by himself (not enough info)
A task to read a String from a file and file not found may ask user to select another file but how can the task now what folder the file might be what extension the file might be. Without knowing that, how can the task create a GUI to re-ask that.
(3): There is no logical (or manageable) way to distinguish between different return.
If a task can't read the file and return null. What about if the file in the wrong format, return null too? How can these two differ? Exceptions can be used to differ that. That why it is called an Exception :-D.
(4): There are many similar tasks that need similar handling and writing that in all tasks is hard to maintain.
Writing the handle code for all access can be a mess as you may require many duplications.
interface DBAccess {
public Result accessDB();
}
class DBOperation {
static public void DoOperation(DBAccess pAccess) {
try { return DBAccess.accessDB(); }
catch(InvalidDBPasswordException IPE) {
// Do anything about invalid password
}
catch(DBConnectionLostException DBCLE) {
// Do anything about database connection lost
}
// Catch all possible DB problem
}
}
...
private User[] ShowUserList_and_ReturnUsers() {
// Find the used.
// Show user list
if (Users.count() == 0)
return null;
else return Users;
// No need to handle DB connection problem here
}
private User[] GetUserProfile() {
// Find the used and return
// No need to handle DB connection problem here
}
...
/** An onClick event to show user list */ {
DBOperation.DoOperation(new DBAccess() {
public Result accessDB() {
return ShowUserList_and_ReturnUsers();
}
});
}
/** An onClick event to show a user profile */ {
DBOperation.DoOperation(new DBAccess() {
public Result accessDB() {
return GetUserProfile();
}
});
}
... Many more DB access
(5): Writing all the checking for error complicate or slow down the task.
The above problem should show how can it help reduce the complication. Here is how it help not to slow down.
for(int i = 0; i < Users.length; i++) {
User aUser = Users[i];
// Do something with user
}
Replaced with
try {
for(int i = 0; ; i++) {
User aUser = Users[i];
// Do something with user
}
}
catch(ArrayOutOfBoundException AOBE) {}
The replacement code will be better performance if the number of user is large.
When a database error occurs, should one return a null value, and error code or throw the exception?
Ans: Depending on what kind of error. Like if you can't find a user, that is not an error. But if the password is wrong or the connection is down, these are errors as trying to handle it in a normal way complicate the program.
(1). Using excessive try-catch() has a negative impact on performance?
Ans: According to "Effective Java", it has very very tiny effect (only not good in loop) as far as I remember (I don't have the book with me here now).
(2).
Using specific exception types is better?
Ans: User specific one is better to avoid solving the wrong problem.
What if i missed to catch one of the possible X types of exceptions that could occur? Frankly, I've heard and use a mere 10% i think of the Java standard exceptions, in 2-3 years.
Ans: Just like if you handle the error without exception, You can miss it too. You simply add it in when you find that out.
Yes, someone said that if the caller don't know how to deal with the trowed exceptions, he SHOULD NOT HAVE THE RIGHT to call the throwing method. Is that right?
Ans: No, if I don't know what to do with some exception, re-throw it.
(3). I've read this article of Anders Hejlsberg, saying that checked exceptions are bad. Should that indicate that convenient exception swallowing is advised in some cases?
Ans: I think he is talking about "Checking exception" as a feature for the compiler to ensure that some exception should be handle. The the idea of having exception.
(4). A picture is worth 1000 words..i guess some examples will help a lot here.
Ans: The code above.
I got the run now .... Sorry ... :-p (Be there in a minute, honey!!)
One thing that we have done on our team is to have custom exceptions for our errors. We are using the Hibernate Validator framework, but you can do this with any framework, or stock exceptions.
For example, we have a ValidationException to handle validation errors. We have a ApplicationException to handle system errors.
You DO want to minimize your try-catch-ing. In our case, we will have the validator collect ALL the validations in "InvalidValue" objects, and then throw a single ValidationException with the invalid value information bundled into it. Then you can report to the user which fields were in error, etc.
In the case you mentioned of a database error - you may not want to send the stacktrace to the UI (logging it is a good idea). This is a case where you can catch the database exception, then throw your own ApplicationException to your GUI. Your GUI won't have to know how to deal with an infinite number of server errors, but can be set to deal with the more generalized ApplicationException - possibly reporting that there is a problem with the server, and indicating that the user should contact your customer support department to report the problem.
Lastly, sometimes you can't help but use a lot of try/catch blocks because of the external APIs you rely on. This is fine. As mentioned before, catch the external exception, and format it into one which makes more sense to YOUR application. Then throw the custom exception.
While I don't have any numbers, I don't believe that try-catch has any significant impact on performance (not that I have seen). I think that if you don't run into many exceptions, the performance impact will be basically nothing. But in any case, it's best to care about implementing code correctly first and achieving good performance second -- a lot easier to do the second once the first is done.
I think the exception class should be specific as to what the exception really is. The problem I have with Java's SQLExceptions is that they give you no information about what really went wrong. Spring uses far a set of more descriptive database exceptions (deadlock exceptions, data integrity exceptions, etc.) That way you can tell what the problem really was.
Checked exceptions can be annoying, but I don't think they're always bad. For example, Spring uses unchecked exceptions for database errors, but I still check for them and either 1) handle them right there, if possible, or 2) wrap in a more general exception that the shows that the component failed.
Unfortunately, I can't think of any good specific exceptions. However, like I said, I've found Spring's exception rules to be helpful and yet not annoying, so maybe you could look at some Spring docs. The Spring database classes are a good example.
Using excessive try-catch() has a negative impact on performance?
This sounds like micro optimization and, if this really has a performance impact, you'll have to deal with a lot of bigger performance problems before to face this one.
Using specific exception types is better? What if i missed to catch one of the possible X types of exceptions that could occur? Frankly, I've heard and use a mere 10% i think of the Java standard exceptions, in 2-3 years. Yes, someone said that if the caller don't know how to deal with the trowed exceptions, he SHOULD NOT HAVE THE RIGHT to call the throwing method. Is that right?
I'm not sure I understood the question but I'd say: "If you don't know what to do with an exception, re-throw it".
I've read this article of Anders Hejlsberg, saying that checked exceptions are bad. Should that indicate that convenient exception swallowing is advised in some cases?
Hell no. This just means that unchecked exception should be preferred in some cases especially when the user won't know what to do with a checked exception (e.g. SQL exception), or if there is not possible recovery,...
A picture is worth 1000 words..i guess some examples will help a lot here.
Spring's DataAccessException is a very good example. Check chapter 10. DAO support.
se-radio made a podcast episode about that topic of error handling that explains some philosophy about how to use exceptions, which can be restated as "Where to absorb them".
The main thing I retained is that most functions should let them bubble up, and most exceptions details should end up in a log file. Then the functions pass only global messages saying that something happened.
In a sense, this leads to a sort of exception hierarchy : one for each layer of code.
As I think they said, it doesn't make sense to explain to the user that such DB cluster failed because the DNS was unavailable, or because the disk was full. At that level, something happend that couldn't allow the transaction to complete, that's all the user has to know.
Of course, the developpers/administrators will be happy to see more details, that's why at the DB layer, the specific exceptions should be logged.
Return value vs. throwing an exception
The fundamental difference between an exception and a return value is that the return value is delivered to your immediate caller, whereas an exception is delivered to a catch clause anywhere in the call stack. This allows to reuse the same exception handler for many different kinds of exceptions. I recommend that you favor exceptions over return codes if and only if you need that feature.
Performance impact.
Every instruction has a negative effect on performance, including those in catch-blocks. However, any modern CPU can throw and handle millions of exceptions per second, so unless you throw thousands of them you won't notice a thing.
Specific exceptions
For throwing, be specific to allow specific handling.
For handling, you can be generic, but you should be aware that arbitrary exceptions can be delivered to your handler, including unchecked ones not declared by your callees.
checked
The debate rages whether methods should use checked or unchecked exceptions.
Never just swallow an exception. Handle or rethrow it. It simplifies maintenance if you don't discard evidence about failures.
Example
An application I worked on recently receives commands over the network which it then executes. This usually involves further interaction with remote systems, which might fail for a host of reasons. The methods to carry out the command don't catch any exceptions, letting them bubble of the call stack to the central exception handler in the command listener, which does the following:
for (int retries = 0;; retries++) {
try {
commandService.execute(command);
return;
} catch (Exception e}
Log.error(e);
if (retries < 3) {
continue;
} else {
saveForAnalysis(command, e);
alertOperator();
return;
}
}
}
We intentionally did not catch & rethrow exceptions in the processing logic, as we felt this would have added no value.
Please, do not return null in case of non-fatal errors. Return a NullObject instead.
Otherwise you need a null check after each and every call to your code which is a pain, and if forgotten will cause the code to crash.

When to choose checked and unchecked exceptions

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?
My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.
Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible.
Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from.
Unchecked Exceptions should be used for everything else.
I'll break this down for you, because most people misunderstand what this means.
Predictable but unpreventable: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure.
Reasonable to recover from: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.
Unless the exception you are throwing meets all of the above conditions it should use an Unchecked Exception.
Reevaluate at every level: Sometimes the method catching the checked exception isn't the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is predictable, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in.
For both checked and unchecked exceptions, use the right abstraction level. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing SQLException or IOException. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. RepositoryException).
From A Java Learner:
When an exception occurs, you have to
either catch and handle the exception,
or tell compiler that you can't handle
it by declaring that your method
throws that exception, then the code
that uses your method will have to
handle that exception (even it also
may choose to declare that it throws
the exception if it can't handle it).
Compiler will check that we have done
one of the two things (catch, or
declare). So these are called Checked
exceptions. But Errors, and Runtime
Exceptions are not checked for by
compiler (even though you can choose
to catch, or declare, it is not
required). So, these two are called
Unchecked exceptions.
Errors are used to represent those
conditions which occur outside the
application, such as crash of the
system. Runtime exceptions are
usually occur by fault in the
application logic. You can't do
anything in these situations. When
runtime exception occur, you have to
re-write your program code. So, these
are not checked by compiler. These
runtime exceptions will uncover in
development, and testing period. Then
we have to refactor our code to remove
these errors.
The rule I use is: never use unchecked exceptions! (or when you don't see any way around it)
There’s a case for the opposite: never use checked exceptions. I’m reluctant to take sides in the debate (there’s definitely good arguments on both sides!) but a fair number of experts feel that checked exceptions were a wrong decision in hindsight.
For some discussion, check the WikiWikiWeb’s “Checked exceptions are of dubious value”. Another example of an early, extensive argument is Rod Waldhoff’s blog post.
On any large enough system, with many layers, checked exception are useless as, anyway, you need an architectural level strategy to handle how the exception will be handled (use a fault barrier)
With checked exceptions your error handling stategy is micro-managed and its unbearable on any large system.
Most of the time you don't know if an error is "recoverable" because you don't know in what layer the caller of your API is located.
Let's say that I create a StringToInt API that converts the string representation of an integer to an Int. Must I throw a checked exception if the API is called with the "foo" string ? Is it recoverable ? I don't know because in his layer the caller of my StringToInt API may already have validated the input, and if this exception is thrown it's either a bug or a data corruption and it isn't recoverable for this layer.
In this case the caller of the API does not want to catch the exception. He only wants to let the exception "bubble up". If I chose a checked exception, this caller will have plenty of useless catch block only to artificially rethrow the exception.
What is recoverable depends most of the time on the caller of the API, not on the writter of the API. An API should not use checked exceptions as only unchecked exceptions allows to choose to either catch or ignore an exception.
You're correct.
Unchecked exceptions are used to let the system fail fast which is a good thing. You should clearly state what is your method expecting in order to work properly. This way you can validate the input only once.
For instance:
/**
* #params operation - The operation to execute.
* #throws IllegalArgumentException if the operation is "exit"
*/
public final void execute( String operation ) {
if( "exit".equals(operation)){
throw new IllegalArgumentException("I told you not to...");
}
this.operation = operation;
.....
}
private void secretCode(){
// we perform the operation.
// at this point the opreation was validated already.
// so we don't worry that operation is "exit"
.....
}
Just to put an example. The point is, if the system fails fast, then you'll know where and why it did fail. You'll get an stacktrace like:
IllegalArgumentException: I told you not to use "exit"
at some.package.AClass.execute(Aclass.java:5)
at otherPackage.Otherlass.delegateTheWork(OtherClass.java:4569)
ar ......
And you'll know what happened. The OtherClass in the "delegateTheWork" method ( at line 4569 ) called your class with the "exit" value, even when it shouldn't etc.
Otherwise you would have to sprinkle validations all over your code and that's error prone. Plus, sometimes it is hard to track what went wrong and you may expect hours of frustrating debugging
Same thing happens with NullPointerExceptions. If you have a 700 lines class with some 15 methods, that uses 30 attributes and none of them can be null, instead of validating in each of those methods for nullability you could make all those attributes read-only and validate them in the constructor or factory method.
public static MyClass createInstane( Object data1, Object data2 /* etc */ ){
if( data1 == null ){ throw NullPointerException( "data1 cannot be null"); }
}
// the rest of the methods don't validate data1 anymore.
public void method1(){ // don't worry, nothing is null
....
}
public void method2(){ // don't worry, nothing is null
....
}
public void method3(){ // don't worry, nothing is null
....
}
Checked exceptions Are useful when the programmer ( you or your co-workers ) did everything right, validated the input, ran tests, and all the code is perfect, but the code connects to a third party webservice that may be down ( or a file you were using was deleted by another external process etc ) . The webservice may even be validate before the connection is attempted, but during the data transfer something went wrong.
In that scenario there is nothing that you or your co-workers can do to help it. But still you have to do something and not let the application just die and disappear in the eyes of the user. You use a checked exception for that and handle the exception, what can you do when that happens?, most of the time , just to attempt to log the error, probably save your work ( the app work ) and present a message to the user. ( The site blabla is down, please retry later etc. )
If the checked exception are overused ( by adding the "throw Exception" in the all the methods signatures ) , then your code will become very fragile, because everyone will ignore that exception ( because is too general ) and the quality of code will be seriously compromised.
If you overuse unchecked exception something similar will happen. The users of that code don't know if something may go wrong an a lot of try{...}catch( Throwable t ) will appear.
Here is my 'final rule of thumb'.
I use:
unchecked exception within the code of my method for a failure due to the caller (that involves an explicit and complete documentation)
checked exception for a failure due to the callee that I need to make explicit to anyone wanting to use my code
Compare to the previous answer, this is a clear rationale (upon which one can agree or disagree) for the use of one or the other (or both) kind of exceptions.
For both of those exceptions, I will create my own unchecked and checked Exception for my application (a good practice, as mentionned here), except for very common unchecked exception (like NullPointerException)
So for instance, the goal of this particular function below is to make (or get if already exist) an object,
meaning:
the container of the object to make/get MUST exist (responsibility of the CALLER
=> unchecked exception, AND clear javadoc comment for this called function)
the other parameters can not be null
(choice of the coder to put that on the CALLER: the coder will not check for null parameter but the coder DOES DOCUMENT IT)
the result CAN NOT BE NULL
(responsibility and choice of the code of the callee, choice which will be of great interest for the caller
=> checked exception because every callers MUST take a decision if the object can not be created/found, and that decision must be enforced at the compilation time: they can not use this function without having to deal with this possibility, meaning with this checked exception).
Example:
/**
* Build a folder. <br />
* Folder located under a Parent Folder (either RootFolder or an existing Folder)
* #param aFolderName name of folder
* #param aPVob project vob containing folder (MUST NOT BE NULL)
* #param aParent parent folder containing folder
* (MUST NOT BE NULL, MUST BE IN THE SAME PVOB than aPvob)
* #param aComment comment for folder (MUST NOT BE NULL)
* #return a new folder or an existing one
* #throws CCException if any problems occurs during folder creation
* #throws AssertionFailedException if aParent is not in the same PVob
* #throws NullPointerException if aPVob or aParent or aComment is null
*/
static public Folder makeOrGetFolder(final String aFoldername, final Folder aParent,
final IPVob aPVob, final Comment aComment) throws CCException {
Folder aFolderRes = null;
if (aPVob.equals(aParent.getPVob() == false) {
// UNCHECKED EXCEPTION because the caller failed to live up
// to the documented entry criteria for this function
Assert.isLegal(false, "parent Folder must be in the same PVob than " + aPVob); }
final String ctcmd = "mkfolder " + aComment.getCommentOption() +
" -in " + getPNameFromRepoObject(aParent) + " " + aPVob.getFullName(aFolderName);
final Status st = getCleartool().executeCmd(ctcmd);
if (st.status || StringUtils.strictContains(st.message,"already exists.")) {
aFolderRes = Folder.getFolder(aFolderName, aPVob);
}
else {
// CHECKED EXCEPTION because the callee failed to respect his contract
throw new CCException.Error("Unable to make/get folder '" + aFolderName + "'");
}
return aFolderRes;
}
It's not just a matter of the ability to recover from the exception. What matter most, in my opinion, is whether the caller is interested in catching the exception or not.
If you write a library to be used elsewhere, or a lower-level layer in your application, ask yourself if the caller is interested in catching (knowing about) your exception. If he is not, then use an unchecked exception, so you don't burden him unnecessarily.
This is the philosophy used by many frameworks. Spring and hibernate, in particularly, come to mind - they convert known checked exception to unchecked exception precisely because checked exceptions are overused in Java. One example that I can think of is the JSONException from json.org, which is a checked exception and is mostly annoying - it should be unchecked, but the developer simply haven't thought it through.
By the way, most of the time the caller's interest in the exception is directly correlated to the ability to recover from the exception, but that is not always the case.
Here is a very simple solution to your Checked/Unchecked dilemma.
Rule 1: Think of a Unchecked Exception as a testable condition before code executes.
for example…
x.doSomething(); // the code throws a NullPointerException
where x is null...
…the code should possibly have the following…
if (x==null)
{
//do something below to make sure when x.doSomething() is executed, it won’t throw a NullPointerException.
x = new X();
}
x.doSomething();
Rule 2: Think of a Checked Exception as an un-testable condition that may occur while the code executes.
Socket s = new Socket(“google.com”, 80);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
…in the example above, the URL (google.com) may be unavailable to due the DNS server being down. Even at the instant the DNS server was working and resolved the ‘google.com’ name to an IP address, if the connection is made to google.com, at anytime afterword, the network could go down. You simply can not test the network all the time before reading and writing to streams.
There are times where the code simply must execute before we can know if there is a problem. By forcing developers to write their code in such a way to force them to handle these situations via Checked Exception, I have to tip my hat to the creator of Java that invented this concept.
In general, almost all the APIs in Java follow the 2 rules above. If you try to write to a file, the disk could fill up before completing the write. It is possible that other processes had caused the disk to become full. There is simply no way to test for this situation. For those who interact with hardware where at any time, using the hardware can fail, Checked Exceptions seem to be an elegant solution to this problem.
There is a gray area to this. In the event that many tests are needed (a mind blowing if statement with lots of && and ||), the exception thrown will be a CheckedException simply because it’s too much of a pain to get right — you simply can’t say this problem is a programming error. If there are much less than 10 tests (e.g. ‘if (x == null)’), then the programmer error should be a UncheckedException.
Things get interesting when dealing with language interpreters. According to the rules above, should a Syntax Error be considered a Checked or Unchecked Exception? I would argue that if the syntax of the language can be tested before it gets executed, it should be an UncheckedException. If the language can not be tested — similar to how assembly code runs on a personal computer, then the Syntax Error should be a Checked Exception.
The 2 rules above will probably remove 90% of your concern over which to choose from. To summarize the rules, follow this pattern…
1) if the code to be execute can be tested before it’s executed for it to run correctly and if an Exception occurs — a.k.a. a programmer error, the Exception should be an UncheckedException (a subclass of RuntimeException).
2) if the code to be executed can not be tested before it’s executed for it to run correctly, the Exception should be a Checked Exception (a subclass of Exception).
You can call it a checked or unchecked exception; however, both types of exception can be caught by the programmer, so the best answer is: write all of your exceptions as unchecked and document them. That way the developer who uses your API can choose whether he or she wants to catch that exception and do something. Checked exceptions are a complete waste of everyone's time and it makes your code a shocking nightmare to look at. Proper unit testing will then bring up any exceptions that you may have to catch and do something with.
Checked Exception:
If client can recover from an exception and would like to continue, use checked exception.
Unchecked Exception:
If a client can't do any thing after the exception, then raise unchecked exception.
Example: If you are expected to do arithmetic operation in a method A() and based on the output from A(), you have to another operation. If the output is null from method A() which you are not expecting during the run time, then you are expected to throw Null pointer Exception which is Run time exception.
Refer here
Here is I want to share my opinion I have after many years of development experience:
Checked exception. This is a part of business use case or call flow, this is a part of application logic we expect or not expect. For example connection rejected, condition is not satisfied etc. We need to handle it and show corresponding message to user with instructions what happened and what to do next (try again later etc).
I usually call it post-processing exception or "user" exception.
Unchecked exception. This is a part of programming exception, some mistake in software code programming (bug, defect) and reflects a way how programmers must use API as per documentation. If an external lib/framework doc says it expects to get data in some range and non null, because NPE or IllegalArgumentException will be thrown, programmer should expect it and use API correctly as per documentation. Otherwise the exception will be thrown.
I usually call it pre-processing exception or "validation" exception.
By target audience. Now let's talk about target audience or group of people the exceptions have been designed (as per my opinion):
Checked exception. Target audience is users/clients.
Unchecked exception. Target audience is developers. By other words unchecked exception are designed for developers only.
By application development lifecycle phase.
Checked exception is designed to exist during whole production lifecycle as normal and expected mechanism an application handles exceptional cases.
Unchecked exception is designed to exist only during application development/testing lifecycle, all of them should be fixed during that time and should not be thrown when an application is running on production already.
The reason why frameworks usually use unchecked exceptions (Spring for example) is that framework cannot determine the business logic of your application, this is up to developers to catch then and design own logic.
We have to distinguish these two types of exception based on whether it is programmer error or not.
If an error is a programmer error, it must be an Unchecked Exception. For example:
SQLException/IOException/NullPointerException. These exceptions are
programming errors. They should be handled by programmer. While in
JDBC API, SQLException is Checked Exception, In Spring JDBCTemplate
it is an Unchecked Exception.Programmer doesn't worry about
SqlException, when use Spring.
If an error is not a programmer error and the reason is coming from external, it must be a Checked Exception. For example: if the
file is deleted or file permission is changed by someone else, It
should be recovered.
FileNotFoundException is good example to understand subtle differences. FileNotFoundException is thrown in case file is not found. There are two reason for this exception. If the file path is defined by developer or taking from end user via GUI it should be an Unchecked Exception. If the file is deleted by someone else, it should be a Checked Exception.
Checked Exception can be handled in two ways. These are using try-catch or propagate the exception. In case of propagation of exception, all methods in call stack will be tightly coupled because of exception handling. That's why, we have to use Checked Exception carefully.
In case you develop an layered enterprise system, you have to choose mostly unchecked exception to throw, but don't forget to use checked exception for the case you cannot do anything.
I agree with the preference for unchecked exceptions as a rule, especially when designing an API. The caller can always choose to catch a documented, unchecked exception. You're just not needlessly forcing the caller to.
I find checked exceptions useful at the lower-level, as implementation detail. It often seems like a better flow of control mechanism than having to manage a specified error "return code". It can sometimes help see the impact of an idea for a low level code change too... declare a checked exception downstream and see who would need to adjust. This last point doesn't apply if there are a lot of generic: catch(Exception e) or throws Exception which is usually not too well-thought out anyway.
Checked exceptions are useful for recoverable cases where you want to provide information to the caller (i.e. insufficient permissions, file not found, etc).
Unchecked exceptions are used rarely, if at all, for informing the user or programmer of serious errors or unexpected conditions during run-time. Don't throw them if you're writing code or libraries that will be used by others, as they may not be expecting your software to throw unchecked exceptions since the compiler doesn't force them to be caught or declared.
Whnever an exception is less likely expected, and we can proceed even after catching that, and we can not do anything to avoid that exception then we can use checked exception.
Whenever we want to do something meaningful when a particular exceptions happens and when that exception is expected but not certain, then we can use checked exception.
Whenever exception navigating in different layers, we don't need to catch it in every layer, in that case, we can use runtime exception or wrap exception as unchecked exception.
Runtime exception is used when exception most likely to be happened, there is no way of going further and nothing can be recoverable. So in this case we can take precautions with respect to that exception. EX: NUllPointerException, ArrayOutofBoundsException. These are more likely to happen. In this scenario, we can take precautions while coding to avoid such exception. Otherwise we will have to write try catch blocks every where.
More general exceptions can be made Unchecked, less general are checked.
I think we can think about exeptions from several questions:
why does exeption happen? What can we do when it happens
by mistake, a bug. such as a method of null object is called.
String name = null;
... // some logics
System.out.print(name.length()); // name is still null here
This kind of exception should be fixed during test. Otherwise, it breaks the production, and you got a very high bug which needs to be fixed immediately. This kind of exceptions do not need be checked.
by input from external, you cannot control or trust the output of external service.
String name = ExternalService.getName(); // return null
System.out.print(name.length()); // name is null here
Here, you may need to check whether the name is null if you want to continue when it is null, otherwise, you can let it alone and it will stop here and give the caller the runtime exception.
This kind of exceptions do not need be checked.
by runtime exception from external, you cannot control or trust the external service.
Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will stop here and give the caller the runtime exception.
by checked exception from external, you cannot control or trust the external service.
Here, you may need to catch all exceptions from ExternalService if you want to continue when it happens, otherwise, you can let it alone and it will stop here and give the caller the runtime exception.
In this case, do we need to know what kind of exception happened in ExternalService? It depends:
if you can handle some kinds of exceptions, you need to catch them and process. For others, bubble them.
if you need log or response to user the specific execption, you can catch them. For others, bubble them.
I think when declaring Application Exception it should be Unchecked Exception i.e., subclass of RuntimeException.
The reason is it will not clutter application code with try-catch and throws declaration on method. If your application is using Java Api which throws checked exceptions that anyways need to be handle. For other cases, the application can throw unchecked exception. If the application caller still needs to handle unchecked exception, it can be done.
The rule I use is: never use unchecked exceptions! (or when you don't see any way around it)
From the point of view of the developer using your library or the end-user using your library/application it really sucks to be confronted with an application that crashes due to an uncought exception. And counting on a catch-all is no good either.
This way the end user can still be presented with an error message, instead of the application completely disappearing.

Categories

Resources