Java catch block, caught exception is not final - java

I am checking out the new features of Java SE7 and I am currently at this point:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
regarding the catch multiple feature, when I came across this statement:
Note: If a catch block handles more than one exception type, then the
catch parameter is implicitly final. In this example, the catch
parameter ex is final and therefore you cannot assign any values to it
within the catch block.
I never noticed that the caught exception is not final in the classic case of handleing caught exceptions.
I just wonder why is that a good thing in the first place? Would it not be ill-advised to essentially MODIFY a caught exception before I guess rethrowing it or maybe logging it's message? Should it not be up to the trowing mechanism to create the exception so it represents exactly what it should?
I have never seen an exception being modified in the catch block can maybe someone point out it's benefits?

It's pretty much the same as method arguments:
You usually don't modify them and many people agree that they should be treated as final (whether or not to actually write final in front of them is a matter of some debate).
But since there's no technical requirement that says it must be final, the language gives you the option to choose.
Personally I know of no good reason to modify the exception reference of a catch-block.

I cannot think of a convincing use-case for modifying an exception in a classic catch clause. However, that doesn't mean it should be forbidden. Especially given that you can modify a parameter variable. If you find this worrisome, you have the option of declaring the exception variable to be final.
On the other hand, allowing modification in the multi-exception catch would introduces the possibility of truly bizarre and confusing code such as this:
catch (IOException | NullPointerException ex) {
...
ex = new IllegalArgumentException(...);
}
I imagine that's what the designers had in mind when they added the restriction in this case.
But either way, this is how the Java language is defined, and what we have to live with. There's not a lot of point in debating the apparent inconsistencies ... unless you are intending to design and implement a new language.

The reason I can think of to enforce it final is due to performance. Once the catch evaluation starts, having a final immutable value in the mechanics of the evaluation ensures a faster evaluation of all catches. Since try-catch is extensively used throughout any java code, the highest performance design is preferable.
Based on the above, it implies a performance improvement that affects most programs.

The idea behind exception-based error handling is that each error should be recovered, if at all possible, at the appropriate level of abstraction. Such error recovery might require information that is not directly available where the exception is actually handled. For this reason it might be convenient to catch the exception, augment it with the relevant information and rethrow it or possibly set it as cause of a new exception object of a more appropriate class.

Related

Catching exceptions properly

I usually tend NOT TO catch "Exception", but only the exceptions i expect methods to throw, i hear often that is good practice.
But today i came across this issue, an IllegalArgumentException thown by the method URLDecoder.decode(string,encoding).
This method is declared as:
public static String decode(String s, String enc)
throws UnsupportedEncodingException{.....
But it then ('if you look at the source') throws IllegalArgumentException in three different places.
So my question to more experienced programmers is, shall i catch "Exception"? or is this method just been declared wrongly?
Thank you
No you should not catch those exceptions. IllegalArgumentException means a precondition has failed. It's usually caused by a bug in your program, and should crash your application. If the input came from the user, detect the wrong input and show a significant message.
If you have an exception handling policy in your application, then you could let this exception bubble out.
There are two main types of Exceptions in Java, ones that are declared (eg UnsupportedEncodingException) and Runtime exceptions which you do not have to catch (eg IllegalArgumentException). However, if you do not catch the Runtime exception it will crash your thread and potentially your whole application, so it depends on your use case. When I am building big applications with several threads and doing several things at once, when I call 'unpredictable' methods like 'decode' (especially anything that takes in user input, or reads from files that I am not in charge of, etc) I like to catch Exception, so that I can log a nice clean error or return a meaningful error to the user, but the rest of my application carries on running normally. But if I am writing a single-threaded application where you run it, provide some input, and it gives some output, I would not bother catching Runtime exceptions as the output and stacktrace will be printed to the console and I can see exactly what the problem is - and it doesn't matter that the application died because I can fix the problem and run it again.
Just my personal preference - hope that helps!
exists two kinds of exceptions in Java, checked and unchecked exceptions, here are the differences:
Unchecked exceptions: they have RuntimeException in its inheritance tree. The compiler doesn´t requires you to catch'em explicitly.
Checked exceptions: They don´t have RuntimeException in its inheritance tree. You have to catch'em in a try-catch block of declare in a throws clausule.
Basically according to all development methodologies, your code have to be tested, you have to cover all scenarios where unchecked exceptions could occur, because they are generated by errors in your logic code or bad usage of API and you have to correct them. That's why in the final code they should never be catched, because they should never happen.
In the other hand the checked exceptions could happen by causes not related to your code logic i.e. Network loose, Changes in the filesystem priviledges, etc. So you should prepare you code to be ready and catch or delegate the exception.
I hope it helps. And sorry for my english
If you take a look at the source of decode(String s, String enc) you will see three places where an IllegalArgumentException is throw:
"Illegal hex characters in escape (%) pattern - negative value"
"Incomplete trailing escape (%) pattern"
"Illegal hex characters in escape (%) pattern -"
All three errors are not usage errors but real errors in the input. So it is correct that IllegalArgumentException is not a checked exception.
It is correct that UnsupportedEncodingException is a checked exception. The caller could handle it.
To answer your question: Be as specific as possible in what you catch. Don't just catch Exception because you will have no easy way to decide how to proceed. You could could catch both UnsupportedEncodingException and IllegalArgumentException in different catch blocks. You must catch UnsupportedEncodingException.

Try-catch: is this acceptable practice?

We have received Java code from a software supplier. It contains a lot of try-catch blocks with nothing in the catch part. They're all over the place. Example:
try {
spaceBlock.enable(LindsayModel);
} catch (Exception e) {
}
My questions are: Is the above acceptable practice? If so, when? Or should I just go ahead and remove all of these "bogus" try and catch statements?
To me this looks like terrible practice, but I'm not experienced enough in Java to tell for sure. Why catch errors if you're not going to do anything with them? Seems to me, you would only do that if you were confident that an exception would be of absolutely no consequence and you don't care if one occurs. However, this is not really the case in our particular application.
EDIT To give some context: We bought a Java-scriptable product from the supplier. Alongside the product, they provided a large proof-of-concept script tailored to our needs. This script came "free of charge" (though we wouldn't have bought the product if it hadn't come with the script) and it "works". But the script is a real pain to build upon, due to many things that even I as a Java novice recognise as awful practice, one instance being this bogus try-catch business.
This is indeed terrible practice. Especially the catching of Exception rather than something specific gives off a horrible smell - even a NullPointerException will be swallowed. Even if it is assured that a particular thrown exception is of no real consequence, one should always log it at the very least:
try {
// code
}
catch (MyInconsequentialException mie) {
// tune level for this logger in logging config file if this is too spammy
MY_LOGGER.warning("Caught an inconsequential exception.", mie);
}
However it is unlikely an exception is completely meaningless in this situation. I recommend researching exactly what exception(s) the application's code is intending to swallow here, and what they would really mean for the execution.
One important distinction is whether the try/catches are used to swallow checked exceptions. If this is the case, it probably indicates extreme apathy on the programmer's part - somebody just wanted his/her code to compile. At the least, the code should be amended:
try {
// code
}
catch (SpecificCheckedException sce) {
// make sure there is exception logging done farther up
throw new RuntimeException(sce);
}
This will rethrow the exception wrapped in an unchecked RuntimeException, effectively allowing the code to compile. Even this can be considered a bandaid however - best practice for checked exceptions is to handle them on an individual basis, either in the current method or farther up by adding throws SpecificCheckedException to the method signature.
As #Tom Hawtin mentioned, new Error(sce) can be used instead of new RuntimeException(sce) in order to circumvent any additional Exception catches farther up, which makes sense for something that isn't expected to be thrown.
If the try/catch is not being used to swallow checked exceptions, it is equally dangerous and should simply be removed.
Terrible, indeed. Swallowing an exception like this can be dangerous. How will you know if something bad has happened?
I'd feel better if the vendor wrote comments to document and acknowledge it ("We know what we're doing"). I'd feel even better if there was a strategy apparent in the code to deal with the consequences. Wrap it in a RuntimeException and rethrow; set the return value to an appropriate value. Anything!
"All over the place"? Are there multiple try/catch blocks littering the code? Personally, I don't like that idiom. I prefer one per method.
Maybe you should find a new vendor or write your own.
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
}
This looks like unfinished code. If the enable method throws an Exception then it will be caught and swallowed by the code. If it doesn't then it does not make sense to try to catch a non occuring exception.
Check to see the methods and where their signatures are not followed by throws exceptionName, then remove the empty try-catch statements from the places they are called.
You can theoretically put try-catch around any statement. The compiler will not complain about it. It does not make sense though, since this way one may hide real exceptions.
You can see this as a sign of bad code quality. You should probably be prepared to run into problems of different type too.
It's not the best:
It hides evidence of the exception so debugging is harder
It may cause features to fail silently
It suggests that the author might actually have wanted to handle the exception but never got around to it
So, there may be cases where this is OK, such as an exception that really is of no consequence (the case that comes to mind is Python's mkdirs, which throws an exception if the directory already exists), but usually, it's not so great.
Unfortunately you cannot just remove it, because it the try block throws a checked exception then it will have to be declared in the throws clause of the method. The callers of the method will then have to catch it (but not if the callers also have this catch (Exception e) {} abomination).
As an alternative, consider replacing it with
try {
meshContinuum.enable(MeshingModel);
} catch (Exception e) {
throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}
Since RuntimeException (and classes that extend it) are unchecked exceptions they do not need to be declared in the throws clause.
What did your contract with the supplier specify? If what they wrote, bad practice and all, meets the spec then they will charge you for a rewrite.
Better to specify a set of tests that will enter many or all of those try-catch blocks and hence fail. If the tests fail you have a better argument to make them fix their terrible code.
Horrible idea on the face of it, totally depends on what you're actually calling. Usually it's done out of laziness or habituated bad practices.
Actually ... not so fast.
There are legitimate cases for ignoring an exception.
Suppose that an exception has happened already, and we're already in a catch(). While in the catch(), we want to make best effort to clean up (which could fail, too). Which exception to return?? The original one, of course. The code looks like this:
try {
something-that-throws();
} catch(Exception e) {
try {
something-else-that-throws();
} catch(Exception e1) {}
throw e;
}
When we really don't care whether an operation succeeds, but (unfortunately) the operation's author throws an exception if a failure occurs.
if (reinitialize) {
try {
FileUtils.forceDelete(sandboxFile); // delete directory if it's there
} catch(Exception e) {}
}
The above saves a rather tortured attempt to see if sandboxFile actually exists before deleting it anyway.

Throws or try-catch

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?
From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?
P.S: Searched through Google and SO but would like a clear answer on this one.
catch an exception only if you can handle it in a meaningful way
declare throwing the exception upward if it is to be handled by the consumer of the current method
throw exceptions if they are caused by the input parameters (but these are more often unchecked)
In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.
And it should catch an exception from a called method it if:
it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).
Here's the way I use it:
Throws:
You just want the code to stop when
an error occurs.
Good with methods that are prone to
errors if certain prerequisites are
not met.
Try-Catch:
When you want to have the program
behave differently with different
errors.
Great if you want to provide
meaningful errors to end users.
I know a lot of people who always use Throws because it's cleaner, but there's just not nearly as much control.
My personnal rule of thumb for that is simple :
Can I handle it in a meaningful way (added from comment)? So put code in try/catch. By handle it, I mean be able to inform the user/recover from error or, in a broader sense, be able to understand how this exception affects the execution of my code.
Elsewhere, throw it away
Note : this replys is now a community wiki, feel free to add more info in.
The decision to add a try-catch or a throws clause to your methods depends on "how you want (or have) to handle your exception".
How to handle an exception is a wide and far from trivial question to answer. It involves specially the decision of where to handle the exception and what actions to implement within the catch block. In fact, how to handle an exception should be a global design decision.
So answering your questions, there is no rule of thumb.
You have to decide where you want to handle your exception and that decision is usually very specific to your domain and application requirements.
If the method where the exception got raised has a sufficent amount of information to deal with it then it should catch, generate useful information about what happened and what data was being processed.
A method should only throws an exception if it can make reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects the method acts upon. For example, a method which is supposed to retrieve from a collection an item which the caller expects to be contained therein might throws a checked exception if the item which was expected to exist in the collection, doesn't. A caller which catches that exception should expect that the collection does not contain the item in question.
Note that while Java will allow checked exceptions to bubble up through a method which is declared as throwing exceptions of the appropriate types, such usage should generally be considered an anti-pattern. Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException, and is expected to throw it when the Moon is full; imagine further, that LookAtSky() calls ExamineJupiter(), which is also declared as throws FullMoonException. If a FullMoonException were thrown by ExamineJupiter(), and if LookAtSky() didn't catch it and either handle it or wrap it in some other exception type, the code which called LookAtSky would assume the exception was a result of Earth's moon being full; it would have no clue that one of Jupiter's moons might be the culprit.
Exceptions which a caller may expect to handle (including essentially all checked exceptions) should only be allowed to percolate up through a method if the exception will mean the same thing to the method's caller as it meant to the called method. If code calls a method which is declared as throwing some checked exception, but the caller isn't expecting it to ever throw that exception in practice (e.g. because it thinks it pre-validated method arguments), the checked exception should be caught and wrapped in some unchecked exception type. If the caller isn't expecting the exception to be thrown, the caller can't be expecting it to have any particular meaning.
When to use what. I searched a lot about this.
There is no hard and fast rule.
"But As a developer, Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check.
By convention, unchecked exceptions should not be included in a throws clause.
Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them."
Source : SCJP 6 book by Kathy Sierra
I ll make it simple for you.
Use throws when you think that the called method is not responsible for the exception (e.g., Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist).
Use try catch block(handle the exception in the called method) when you think that your functionality in the called method may result in some exception
If you use a try catch, when the exception occurs, the remaining codes would be still executed.
If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.
try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....
But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....
Hope it is correct :-)

Is there a limit on the number of exceptions I should throw from a method?

Will declaring the function in this way have any implications on the performance?
public init(){
try{
initApplication();
}catch(A1Exception){
}catch(A2Exception){
...
}catch(A5Exception){
}
}
private void initApplication() throws A1Exception, A2Exception, A3Exception, A4Exception, A5Exception {
initApp1(); //throws A1, A2, A3
initApp2(); //throws A4, A5
}
Are there any issues with implementing initApplication() in this way?
In recent years there's been a feeling that checked exceptions are fairly harmful. Each of these exceptions, if they are checked, forces the calling methods to have to handle them or declare them. This breaks encapsulation, because now something of the lower level implementation details leaks up into the higher levels.
Joshus Bloch talks about this in Effective Java, which I highly recommend.
There is no limitation as to how many exceptions can be thrown by a method.
The more exception you throw, the more you can be specific about any exceptions being caught.
Just I would like to point out a few suggestions which I follow.
1) Atleast have a generic exception at the last so if any other exception which may occur in your code is caught than being thrown to the calling class.
2) You can have category of Exception Classes like BusinessLogic Exception, InvalidDataException, SystemsException so you may have actually less no of exceptions being thrown from any method. (Unless your business demand exact exception
3) Always have error codes than throwing actual text messages which will make your application language independant.
I don't see a problem throwing whatever Exception your code requires. My first impression when looking at the example is that Exceptions might be used here to control the flow of your application. Be careful not to do that. Exceptions should only be triggered in exceptional cases.
One reason why process flow should not be handled via Exceptions is that raising Exceptions is an expensive process. Though the structure of multiple catch blocks shouldnt result in a performance hit, the (potential) underlying process that uses Exceptions to control flow would not perform well.
With that in mind, is there a 'smell'? Only if the above concern is true in the design of the code.
Q1. Will this have performance impact?
No, not if they are 'genuine' exceptions (i.e. not being used for normal program control flow)
Q2. Do you see smell in initApplication()?
No, not if initApplication() can be expected to raise N exceptions, i.e. if there are N - exceptional circumstances that could prevent initApplication() from completing it's work.
1: The performance impact will be minimal...
2: But it's not necessarily a good idea, as having excessive boiler plate code makes it hard to read. If every exception is going to be handled the same way, then you should either do a catch of the base class Exception. Or you can have initApplication() throw a custom exception -- something like ApplicationInitializationException, which conveys a little more meaning about what went wrong. You can set the message for the exception to be the exact details.
There are some cases where you might get 5 different exceptions, and might have to deal with all of them differently. In that case, catching all 5 would be the proper thing to do. But it's worth thinking about if that's really necessary before you implement it.
If there is no exception there is no performance impact, if an exception is thrown, there is some overhead finding the matching catch which will grow as you add more exceptions, but it should not matter, because exceptions should be er.. exceptional. The should not happen under ordinary circumstances.
In other words if you do not use throwing exceptions to control the flow of your program yuo should be ok, and if you do this is certainly a smell no matter how many catch clauses you have
On a purely technical note, the class file format introduces an upper limit of 65536 exceptions. The u2 type of exceptions_table_length is shorthand for an unsigned two byte quantity.
The Code attribute has the following format:
Code_attribute {
u2 attribute_name_index;
u4 attribute_length;
u2 max_stack;
u2 max_locals;
u4 code_length;
u1 code[code_length];
u2 exception_table_length;
{ u2 start_pc;
u2 end_pc;
u2 handler_pc;
u2 catch_type;
} exception_table[exception_table_length];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
I only bring this up in case you are generating code. JSP developers often have to worry about problems with generated methods exceeding 64KB code size. This and other limitations are listed in Section 4.10 Limitations of the Java Virtual Machine.
I guess this answer is mostly related to the Q2 but view of it that is not so technical but might be worth considering anyway are the one behind the following two questions?
Does it make sense for the user to catch all of them?
Do you want to risk the user getting fed up with having lots of catch blocks and instead just insert a single "catch(Exception ex) {// ex.printStackTrace(); // enable this if we see problems}" or something similar and stupid.?
In this case I guess it might not be relevant but I think it is worth considering when doing API design in general.
Do not throw any exceptions unless you are going to take an action if an exception is caught. Convert your checked exceptions to runtime exceptions for logging purposes.
More info on the topic can be found here

Java exception handling idioms ... who's right and how to handle it?

I currently have a technical point of difference with an acquaintance. In a nutshell, it's the difference between these two basic styles of Java exception handling:
Option 1 (mine):
try {
...
} catch (OneKindOfException) {
...
} catch (AnotherKind) {
...
} catch (AThirdKind) {
...
}
Option 2 (his):
try {
...
} catch (AppException e) {
switch(e.getCode()) {
case Constants.ONE_KIND:
...
break;
case Constants.ANOTHER_KIND:
...
break;
case Constants.A_THIRD_KIND:
...
break;
default:
...
}
}
His argument -- after I used copious links about user input validation, exception handling, assertions and contracts, etc. to back up my point of view -- boiled down to this:
"It’s a good model. I've used it since me and a friend of mine came up with it in 1998, almost 10 years ago. Take another look and you'll see that the compromises we made to the academic arguments make a lot of sense."
Does anyone have a knock-down argument for why Option 1 is the way to go?
When you have a switch statement, you're less object oriented. There are also more opportunities for mistakes, forgetting a "break;" statement, forgetting to add a case for an Exception if you add a new Exception that is thrown.
I also find your way of doing it to be MUCH more readable, and it's the standard idiom that all developers will immediately understand.
For my taste, the amount of boiler plate to do your acquaintance's method, the amount of code that has nothing to do with actually handling the Exceptions, is unacceptable. The more boilerplate code there is around your actual program logic, the harder the code is to read and to maintain. And using an uncommon idiom makes code more difficult to understand.
But the deal breaker, as I said above, is that when you modify the called method so that it throws an additional Exception, you will automatically know you have to modify your code because it will fail to compile. However, if you use your acquaintance's method and you modify the called method to throw a new variety of AppException, your code will not know there is anything different about this new variety and your code may silently fail by going down an inappropriate error-handling leg. This is assuming that you actually remembered to put in a default so at least it's handled and not silently ignored.
the way option 2 is coded, any unexpected exception type will be swallowed! (this can be fixed by re-throwing in the default case, but that is arguably an ugly thing to do - much better/more efficient to not catch it in the first place)
option 2 is a manual recreation of what option 1 most likely does under the hood, i.e. it ignores the preferred syntax of the language to use older constructs best avoided for maintenance and readability reasons. In other words, option 2 is reinventing the wheel using uglier syntax than that provided by the language constructs.
clearly, both ways work; option 2 is merely obsoleted by the more modern syntax supported by option 1
I don't know if I have a knock down argument but initial thoughts are
Option 2 works until your trying to catch an Exception that doesn't implement getCode()
Option 2 encourages the developer to catch general exceptions, this is a problem because if you don't implement a case statement for a given subclass of AppException the compiler will not warn you. Ofcourse you could run into the same problem with option 1 but atleast option 1 does not activly encourage this.
With option 1, the caller has the option of selecting exactly which exception to catch, and to ignore all others. With option 2, the caller has to remember to re-throw any exceptions not explicitly caught.
Additionally, there's better self-documentation with option 1, as the method signature needs to specify exactly which exceptions are thrown, rather than a single over-riding exception.
If there's a need to have an all-encompassing AppException, the other exception types can always inherit from it.
The knock-down argument would be that it breaks encapsulation since I now I have to know something about the subclass of Exception's public interface in order to handle exceptions by it. A good example of this "mistake" in the JDK is java.sql.SQLException, exposing getErrorCode and getSQLState methods.
It looks to me like you're overusing exceptions in either case. As a general rule, I try to throw exceptions only when both of the following are true:
An unexpected condition has occurred that cannot be handled here.
Somebody will care about the stack trace.
How about a third way? You could use an enum for the type of error and simply return it as part of the method's type. For this, you would use, for example, Option<A> or Either<A, B>.
For example, you would have:
enum Error { ONE_ERROR, ANOTHER_ERROR, THIRD_ERROR };
and instead of
public Foo mightError(Bar b) throws OneException
you will have
public Either<Error, Foo> mightError(Bar b)
Throw/catch is a bit like goto/comefrom. Easy to abuse. See Go To Statement Considered Harmful. and Lazy Error Handling
I think it depends on the extent to which this is used. I certainly wouldn't have "one exception to rule them all" which is thrown by everything. On the other hand, if there is a whole class of situations which are almost certainly going to be handled the same way, but you may need to distinguish between them for (say) user feedback purposes, option 2 would make sense just for those exceptions. They should be very narrow in scope - so that wherever it makes sense for one "code" to be thrown, it should probably make sense for all the others to be thrown too.
The crucial test for me would be: "would it ever make sense to catch an AppException with one code, but want to let another code remain uncaught?" If so, they should be different types.
Each checked Exception is an, um, exception condition that must be handled for the program behavior to be defined. There's no need to go into contractual obligations and whatnot, it's a simple matter of meaningfulness. Say you ask a shopkeeper how much something costs and it turns out the item is not for sale. Now, if you insist you'll only accept non-negative numerical values for an answer, there is no correct answer that could ever be provided to you. This is the point with checked exceptions, you ask that some action be performed (perhaps producing a response), and if your request cannot be performed in a meaningful manner, you'll have to plan for that reasonably. This is the cost of writing robust code.
With Option 2 you are completely obscuring the meaning of the exception conditions in your code. You should not collapse different error conditions into a single generic AppException unless they will never need to be handled differently. The fact that you're branching on getCode() indicates otherwise, so use different Exceptions for different exceptions.
The only real merit I can see with Option 2 is for cleanly handling different exceptions with the same code block. This nice blog post talks about this problem with Java. Still, this is a style vs. correctness issue, and correctness wins.
I'd support option 2 if it was:
default:
throw e;
It's a bit uglier syntax, but the ability to execute the same code for multiple exceptions (ie cases in a row) is much better. The only thing that would bug me is producing a unique id when making an exception, and the system could definitely be improved.
Unnecessary have to know the code and declare constants for the exception which could have been abstract when using option 1.
The second option (as I guess) will change to traditional (as option 1) when there is only one specific exception to catch, so I see inconsistencey over there.
Use both.
The first for most of the exceptions in your code.
The second for those very "specific" exceptions you've create.
Don't struggle with little things like this.
BTW 1st is better.

Categories

Resources