Which way is better for exception handling - java

Which is a better approach to exception handling and why?:
(1) Defining a single exception for the whole application which takes a string message and displays it. Use this exception everywhere with a specific message appropriate to the scenario.
I have no idea why this is not appropriate.
(2) Defining a new exception class for each different case in the application.
I feel this is not appropriate because there are cases where the exception is at just one place in the application. e.g. amount entered is -ve Is it ok to create a whole new exception class just for a single case in the app ?

Define a new exception for each kind of error that matters to your user. So, for example, ideally you should catch NullPointerException inside your program, and turn it into a CustomerLookupException to that the user level of the program can report "Software error retrieving customer." Exception chaining is handy for this, as you can pass along the original exception as well.
The whole Java Tutorial on exceptions is a good resource.

Definitely defining new exception for all different cases.
Imagine you are implementing an interpreter/compiler. You gonna have modules as SemanticVerifier, Interpreter, CodeGenerator (and others of course). You want to know what kind of exception gonna be thrown when your program crash. Oh there it's Semantic! there look it's a bug in the Interpreter! And you want the user to know so he can report a more precise bug.
I personally think it leads to a better design if you have separate exceptions for every module.

You should define a new exception for each case.
The reason is so that each Exception can be handled independently.
For example, catching the Exceptions differently allows you to either continue in some cases, or end in others.

in my view your 1st option is more suitable
(1) Defining a single exception for whole application which takes a string msg and displays it. And using it at all places with appropriate place specific message.
Even i am using a single exception in the application. If you create separate exception for each type it will increase complexity. It will have lot of redundant code.
For denoting different type of exception, you can pass a parameter(type or something) in the common exception itself.

Related

Does it make sense to throw an exception which is always chained?

I'm working on a message library and the send method of an object can fail for a number of reasons such as the socket being closed, etc.
I favor checked exceptions over runtime exceptions but I'm wondering if it would then be more appropriate to favor chaining the exceptions early such that the underlying exception is always wrapped in another, more generalized exception.
For example, a message may only throw a checked SendFailedException but the cause() would be more specific such as SocketClosedException. This feels like it would be less cluttered than having all of the checked exceptions being thrown individually.
Inheritance doesn't quite work here as a SocketClosedException can be thrown for other methods as well. And not every closed exception is a result of a failure to send.
Would it be appropriate to wrap further information in cause() or would this end up being more confusing? I don't recall finding exceptions functioning in this way in the wild and this might be unconventional and confusing for others.
Does Java or other libraries ever do this? Is it appropriate for my use case?
Would it be appropriate to wrap further information in cause() or
would this end up being more confusing ?
You can always use cause to wrap the original exception which will provide more details about the root/origin of the exception in the stacktrace. You can refer Exception API here which explains how cause can be set to wrap exceptions.
Does Java or other libraries ever do this? Is it appropriate for my
use case ?
In many libraries, this pattern is followed, just to pin point, in spring-mvc, NestedServletException will be thrown by the container which will wrap the original exception with the cause. Yes, in your case, you can throw SendFailedException by setting the cause as SocketClosedException.
Also, if your message library is from third party, ensure that the 3rd party Exception classes don't spread across your project/classes, rather wrap/convert them into your own Exception classes so that your code is not tightly coupled with 3rd party Exception classes (even if you have to migrate from it).

Throwing immediately wrapped exceptions

Does it make sense to immediately wrap and throw exceptions to provide more context/reason as to why the exception was thrown?
For example, assuming CustomException is a custom exception for the particular application/module:
throw new CustomException(new UnsupportedOperationException("Feature X is no longer supported. :("));
Would it be more standard to simply pick one or the other? For example:
throw new CustomException("Feature X is no longer supported. :(");
or
throw new UnsupportedOperationException("Feature X is no longer supported. :(");
I understand that it's fairly standard practice to throw wrapped exceptions if they're being rethrown / from a catch block but I don't think I've seen throwing wrapped exceptions from scratch (using new).
I can't think of a case where creating a wrapped exception like this is a good idea.
Filling in stack traces is relatively expensive, and creating a duplicate stack trace is a waste.
Exception chaining and suppressed exceptions are primarily for logging; applications that inspect this information in order to control flow are fragile. Any extra information you want to convey can be put in the message for logging with the stack trace.
The exception mechanism is based on the exception type, and handlers should primarily rely on that for flow control. If additional information is needed, it can be exposed through specific API on the custom exception.
In the case of a deprecated API, throwing UnsupportedOperationException is the best choice. It is a programming error to upgrade a library to an incompatible version. This doesn't occur unpredictably at runtime; the developer can and should discover this problem during development.
If runtime exceptions are caught, it should be at a high level in the application. For example, a Servlet engine might catch and report runtime errors without aborting the whole process, protecting other applications. A GUI might catch runtime exceptions arising from event dispatch without crashing the whole application.
In other cases, throwing a new CustomException might be better. A subclass of CustomException could be used to report a type of error that might be recoverable. For example, suppose usernames must be unique. Your application could check to see if a username is taken, and then create an account if the name is available, but this introduces a race condition where another user might claim that name in the meantime. By attempting optimistically to create the user account, and failing with a specific DuplicateUsernameException if the username is not available, a handler can prompt for a new username.
For your case I would say
throw new CustomException("Feature X is no longer supported. :(");
Unless you want top level component to know what you are throwing.
This can be either
1. DAO related
2. Any exception would cause another exception
3. multiple exception would occur
For example if this feature X if yours might throw IOException and FileNotFoundException. You dont want to return both to the upper component then you should wrap it. But you know the feature X doesn't have any impact to the caller class then you can just end it with the custom exception.
Does it make sense to immediately wrap and throw exceptions to provide more context/reason as to why the exception was thrown?
When you catch an exception and wrap it, this makes perfect sense. Adding the context information is one reason to do it. Another reason is to make it a different kind of exception altogether in order for it to be suitable for the callers of your API (as opposed to being suitable to your API's implementation).
Consider an example: your library uses an RDBMS backend to store some data, with referential integrity constraints turned on. One of these constraints could reject duplicate records of some kind for the same user ID. In this case your library would catch SQLException indicating that the referential integrity constraint is violated. However, your library should not throw SQLException to its users. Instead, it should throw a custom DuplicateUserRecordException with user ID and SQLException inside.
However, creating an exception with another exception nested inside (i.e. doing literally what your first example does) is not a good idea. The main reason for wrapping an exception inside another exception, as opposed to providing an unrelated exception, is to retain the place where the exception has been thrown. However, your nested exception is never thrown, so it has no useful context embedded inside it.

What is an efficient method to map errors(exceptions) occuring in a J2EE website with suitable error messages?

I am developing a J2EE website for a mini project, and I’m puzzled about exception handling. I have defined several custom exception classes, and they’re thrown from several parts of the website, and they are captured in a custom exception handler. But, i am yet to find a good way to map the occurred Exception to an error message.
To put it simply, if an exception occurs somewhere, I have a global exception handler which captures the thrown exception ( i won't swallow it within a local catch block ), but i need an efficient mechanism by which i should be able to convert it into a suitable error message to be displayed to the end users.
Also, the custom exceptions have a tree hierarchy , which means the top of the tree will have general exceptions and the leaves of the tree would have exceptions defined for a very specific purpose.
The tree would be like
CustomException
Type1Exception
Type11Exception
Type12Exception
Type121Exception
Type122Exception
Type13Exception
Type2Exception
Type21Exception
Type211Exception
Type22Exception
Type3Exception
Type31Exception
Type32Exception
Type33Exception
Type4Exception
Type41Exception
Type411Exception
Type4111Exception
Type4112Exception
Type421Exception
Type4211Exception
Type42Exception
Each exception branch would represent exceptions occurring in specific part of the website. The tree will grow more in future, if more features are added to the website What is the best practice to map the bunch of exceptions to error messages ?
And, is using instanceOf operator and isInstance() method , to check the type of exception, a good practice (in aspects of performance ,scalability and code standards) ?
Each exception branch would represent exceptions occurring in specific
part of the website.
But what if the exception happens in a common component shared by different parts of the website?
Exceptions already tell you where they happened (that's what the stacktrace is for), you don't need to put it in the name. The name is for the reason of the exception (such as IllegalArgumentException or EOFException.
Your design is poor in many ways. You should handle exceptions where you can, either locally with a specific error message (if let's say a user wants to pick a username that's already taken) or globally with a general error message.
Edit:
There are thousands of potential error situations in an application. You can divide them into categories based on what you can do to them. Let's say you try to insert a duplicate username into the database, and an exception is thrown. You catch this and tell the user to choose a different username.
That's the least exceptional case, you might even bypass this by checking if the username exists, instead of relying on an exception.
Then you have a bit more exceptional, let's say you can't connect to the database at all. You don't know why, but you're still prepared, you tell the user that something is wrong with the database, and please try again.
Then you have the most exceptional. You're not prepared for it, you don't have a catch clause for it, it flies up to the global exception handler. All you can do is show the user a generic error message that "Something went wrong", log the error, and notify the maintenance team.
Now the way to design exceptions is based on how much information you know about what happened. You might have a DatabaseException class for all DB related errors, and a DuplicateUserException that extends it to provide more detail. Also note that a DuplicateUserException would never propagate up to a global exception handler. You'd handle it right there, showing the user the screen with the error message. The error message which you'd get from a resource bundle not with the name of the exception, but a general key, such as "exception.user.duplicate".
I think your basic mistake is thinking that you can create a single place responsible for exception handling, just based on the exception type. I suggest that you let that idea go. The global handler should only handle (mainly log) the exception when nobody else will.

Which is better ? Many custom exception classes, or one exception class with many custom exception codes?

In a standard J2EE web application , assuming that class load times during app startup is not an issue, which would be a better approach in terms of maintainance, performace and usability ?
The first approach involves creating different exception classes, each to denote a particular error that occurs in the application. The class names are self explanatory, and that'll be used to provide error messages.
(UPDATE : The number of classes is about 30 as of now, and it'll continue to increase in the near future, probably upto 70 or 80 atmost)
The secodn approach involves creating one exception class, and a bunch of exception codes where each code represent a particular error in the app. The error codes are obtained from the exception, and is used to provide error messages.
It is more or less dependent on your business needs.
From my point of view, having multiple custom exception classes is the right approach to go.
Learn from Java, how many it manages.
In any given application there can be n type of validations, few can be clubbed under one group, few into another, but fitting everything into single does not solve the purpose in terms of logic and business.
let say,
UserAuthenticationException
Cases it can cover up, and give different error messages for different cases.
1.) Invalid username/passwords
2.) Session timeout
3.) Multiple active token of same user in different machines etc...
Later playing with instanceof or creating handlers of say different exception classes is much more easier rather playing with messages.
The choice is ultimately up to you, as both can be valid. I personally find it is better to make many custom exceptions, particularly if they are going to be used multiple times for the simple fact that if I want to change the error code or message a certain type of exception "File did not successfully upload" or "Item not found" or whatever the case may be, I only have to do it in one place, the custom exception, and not in every place which uses it.
This also allows you do catch those specific exceptions as the are thrown in other parts of your code. Perhaps you need to do extra work if the exception was a "File not found" exception, in which case you can catch only those exceptions that you want to handle in different ways - this would be much more difficult if they were all the same class.
Classes exists in OOP for a reason and you should take advantages of those reasons.
From the code maintabaility point of view, the first approach, as it results in cleaner/simpler code. The name of the exception class gives you the cause of the problem without having to inspect the attributes of the exception class.
From the performance point of view, the second approach, "fewer exception classes mean a smaller
memory footprint and less time spent loading classes" (Effective Java, item 60). Keep in mind however, that "premature optimization is the root of all evil" so until you confirm your application has performance issues do not try to optimize it.
Most exceptions within an application are handled by some generic recovery; probably involving generating a log file and killing or restarting the process. There's no reason for these to be different types.
In the less usual case where a specific recovery procedure is expected, there should be a specific error class for that procedure.

java - is there a standard way of collecting exceptions?

I have a Java program that parses several different input files. Even when an error is found in this input files, parsing could still continue and collect several other errors too. So what I want to do is instead of throwing and exception and stopping parsing process, I'd like to register the exception to somewhere, and then continue parsing and collect several other errors in similar way, then in the end I want to check if any errors are reported, and fail or continue depending on this.
Of course I can always do this manually by writing ExceptionRegister or whatever classes but I want to know two things:
1) Is there a problem with this approach? Do you know any alternative designs for what I want to do?
2) Is there a standard way of doing this? (e.g. instead of rolling my own classes I'd like to use built-in functionality if possible)
Thanks
EDIT: I don't know why but someone just removed his answer just before I accepted his answer. Anyway, I think simple data structures should work. Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
EDIT2: Here are more clarifications. My problem has nothing to do with parsing. Parsing was just an example because my program does some parsing. Think this: I'm running an algorithm and in case of an error, I can continue the algorithm to collect more errors so that instead of printing one error and when it's fixed, printing second error, I can print this two errors together.
Exceptions should really be used when you can't handle the input anymore. They are the special case where your code says "I give up, I'm missing some information or I wasn't meant for this". This is a grey area on how to define such cases, but the usual philosophy, as put by Bill Venners in this (old!) article is:
Avoid using exceptions to indicate conditions that can reasonably be
expected as part of the typical functioning of the method.
In your case, it sounds like the content you have to parse might be incorrect, but this is expected by your program and doesn't break enough the contract to stop the parsing. On the other hand, an acceptable exception would be valid to use if an error in the syntax of the input causes the rest of the interpretation to fail, for example.
But people still uses exception because they are quite convenient for stopping execution and going up the stack without going in the tedious details of flowing through returns of results. But on its counterpart, they can have tricky results as you leave some unattended state in some objects.
Your requirements sounds more like a validation pattern is required than one single exception that could cause the processing to stop. One exception to stop all processing: if you throw one, the rest will be ignored. But you suggested that you would collect them instead of throwing those. So I'd say, in that case, why use exceptions at all? It seems you do want to return proper results and not stop the program's execution.
Because if you still go down this path, you could have a collection of exceptions to throw at the end. Which one do you throw? Which one takes precedence, in the Exception collector you created?
Take the example of Eclipse, which has this gigantic platform to handle with a massive collection plug-ins contribution. They use a proper communication channel to log any warning and errors, either in problems pane or through the execution of background task. The latter's execution will usually return an IStatus object or a variant. Based on this IStatus object, the code that receives the status decides to act upon it.
Hence personally, I'd develop a similar object that would collect all necessary user's errors (and not program's errors), that does not break the program's execution and an acceptable part of the contract. This object can contain the severity of the error, its source, a hint on how to fix it (this can be a string, or even a method that contains a pinpointing logic for showing the error or possibly a partial automated fix), etc... Once the execution is done, the parsing's result will get these status objects and act on it. If there are errors, inform the user through the UI and log it as well.
So it's basically the same approach as you initially suggested, minus the exceptions and minus the commodity of jumping through the stack that could lead to nasty side-effects and very difficult to debug errors.
I think I understand now. What you are actually trying to do is to collect the parse errors (which you are representing as exceptions) and continue parsing the current input file.
There is no standard way to do this:
The "exception register" is really nothing more than a list of parse error descriptors ... presumably some parser exception. If you can catch the exception at the appropriate point, it is trivial to add it to the "register".
The difficult part is the functionality you are not talking about:
How to capture the location of the error
How to get the parser to continue parsing when it gets a parser error.
The solutions to these depend on how you have implemented your parser.
If you are using a parser generator, there is a good chance that the PGS documentation explains how to implement this.
If you are implementing the parser by hand, you will need to roll your own code to track error locations and do syntax error recovery.
Basically, I'll write an exception class that collects several error messages. Then I'll call it's throw method which throws itself if it has at least one error message registered.
That sounds like an abuse of exceptions. A better idea is to accumulate the errors in a list, and then create / throw the exception if the list is non-empty. Use a static method in a helper class if you want to avoid duplicating code.
An exception that conditionally throws itself is (IMO) bizarre! And creating lots of exceptions that you are unlikely to throw is likely to be inefficient. (Depending on the JVM, the expensive part of exceptions is often creating the exception and capturing the stack frames. The expense can be significant.)

Categories