I need to know if doing less Try and doing more Catchs is a good way to control a flux what is very important in exception control terms.
Because in the flux this should never go on if there's something goes wrong!
i'm not trying to save code lines, i need something visually easy to understand and functionally in code terms
Var ix;
Var iy;
Var iz;
try {
try {
do something ix;
} catch (Exception ex1) {
ex1.printStackTrace();
}
try {
do something iy;
} catch (Exception ex2) {
ex2.printStackTrace();
}
do something iz;
} catch (Exception ex3) {
ex3.printStackTrace();
}
OR
Var ix;
Var iy;
Var iz;
try {
do something ix;
do something iy;
do something iz;
} catch (Exception ex1) {
ex1.printStackTrace();
} catch (Exception ex2) {
ex2.printStackTrace();
} catch (Exception ex3) {
ex3.printStackTrace();
}
Those two examples will actually behave differently. In the second, if an exception is caught then none of the following do something will run. In the first they can each fail independently.
Always catch exception in as small and limited scope as possible; using too broad catches like
} catch (Exception ex) {
// wrong. use explicit exceptions,
// e.g. catch(NullPointerException ex) instead, possibly with multicatch
or catches on too big scope
try {
//... tons of code
} catch (IOException ex) {
// and the exception happened WHERE?
}
is an anti-pattern by itself.
This thing said, all that other people said is correct. The codes will behave differently, because nested catches actually handle the exception encountered within and not propagate it outside.
Multiple catches on e.g. Exception (replace with e.g. NullPointerException and the idea is still there) done in this fashion
try {
try {
// some code
} catch (Exception ex1) { /* stack dump or whatever */ }
} catch (Exception ex2) { /* stack dump or whatever */ }
won't work good too, because inner Exception is a valid catch for every exception of a given kind (in this case - every exception at all) - thus nothing catchable will propagate outside of it to the outer try/catch block.
Another thing (already stated countless times too) is that you should either cure the exception, throw it up (propagate) or die with the exception. Simply doing a stack dump is like saying 'you, my dear sir, have cancer'. It doesn't improve the situation for anybody. If you can't help it, propagate it. If nothing can handle it, die with some grace (stack dump is hardly a gracious way for a thread to die...).
And yet another thing to distinguish is Java's Throwable types, i.e. error vs checked/unchecked exception difference. In general:
Error should cause the thread to die immediately, because it signifies a serious VM/hardware error,
unchecked exception (RuntimeException comes to mind) is a really exceptional case, impossible or very hard to predict, so it should usually NOT be contained and rather just signaled to the user with programatic fallback to last validly executed code branch,
checked exception is a common exceptional case, which, in turn, MUST be handled by the programmer explicitly and shouldn't disrupt program execution.
tl;dr - please learn the rationale about using exceptions before actually using them.
Further reading: http://docs.oracle.com/javase/tutorial/essential/exceptions/ and http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 (Item 39: Use exceptions only for exceptional conditions, Item 40: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors, Item 41: Avoid unnecessary use of checked exceptions, Item 43: Throw exceptions appropriate to the abstraction. )
The two ways are logically different. In the first way, you will try to do action "iy" even if action "ix" throws an exception. In the second way, if action "ix" throws an exception, then "iy" and "iz" will never be executed.
I would say it depends on what you want. Are any of your exceptions recoverable? Do you want to keep going after encountering an exception? These kind of things determine how you handle exceptions. Or at least, how I do.
This is very different !
In your first code :
If ix triggers ex1, it will continue to iy. But if it triggers ex3,
everything will stop.
If iy triggers ex2, it will continue to iz. But if it triggers ex3, everything will stop.
In your second code :
if an exception is thrown, everything will stop.
You should read this tutorial.
There is no single, correct answer to your question. It depends. As you can see from other answers your first and second code differs how in execution (some operations might be skipped in second example).
You should focus on:
type of exceptions you are catching (are those exceptions different, do you want to handle them differently?),
how you are going to handle the exception,
is one exception affecting other pieces of your code,
are two or more exceptions going to be catch by single catch statement,
etc.
You should consider each solution for given circumstances.
Related
I have a requirement where in program execution flow should continue even after throwing an exception.
for(DataSource source : dataSources) {
try {
//do something with 'source'
} catch (Exception e) {
}
}
If exception is thrown in the first iteration, flow execution is stopped. My requirement is even after throwing exception for the first iteration, other iterations should continue.
Can i write logic in catch block?
Well first of all ,
There are 2 types of Exceptions. Checked & Unchecked.
Unchecked exceptions are the ones that your program cannot recover from. Like NullPointers, telling you that something is really wrong with your logic.
Checked exceptions are runtime exceptions, and from these ones you can recover from.
Therefore you should avoid using catch statemens looking for the "Exception" base class. Which are represent both times. You should probably consider looking for specific exceptions(normally sub-classes of Run-Time exceptions).
In short, there is much more into that.
You should also keep in mind that you shouldn't use exception handling as workflow. usually indicates that your architecture is somehow deficient. And as the name states, they should be treated as "exceptions" to a normal execution.
Now, considering you code :
for(DataSource source : dataSources) {
try {
//do something with 'source'
} catch (Exception e) { // catch any exception
continue; // will just skip this iteration and jump to the next
}
//other stuff ?
}
As it is, it should catch the exception and move on. Maybe there is something your not telling us ? :P
Anyway, hope this helps.
If you are not breaking the loop somehow inside the catch block, then the other iterations will just continue, regardless of whether an exception was thrown in a previous iteration.
Try this simple example and see what happens:
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
for(String str: list) {
try {
System.out.println(str);
throw new Exception("Exception for string " + str);
} catch(Exception ex) {
System.out.println("Caught exception");
}
}
You will see that all iteration execute, even though each one throws an exception.
If an exception occurs on the for(DataSource source : dataSources) while calling dataSources to initialize the iterator, then that exception will not be caught.
Is that what you mean by "If exception is thrown in the first iteration, flow execution is stopped."?
If this is the case, then there's nothing else you can do and the loop should not execute any interations.
The logic you have there now does exactly that. If the exception puts DataSource into an invalid state, the next attempt to use the iterator may throw a different exception, but that's a different matter and something specific to DataSource (so you'd have to look at whether DataSource lets you do something to deal with that other invalid state in some way). But in the general case, you're doing it right.
No, there is no language support for handling an exception and then jumping back to the statement that caused it. You have to wrap separate try...catch constructs around every subsequence of operations that should execute even if the previous subsequence threw an exception.
I wrote the following code recently; it uses a lot of exception handling. I think it makes the code look very unreadable. I could shorten the code by catching generic exception, such as
catch (Exception e){
e.printStackTrace();
}
but I also heard that catching generic exception is not a good coding practice.
public class DataAnalyzerTester {
/**
* #param args args[0] stores the filename
* #exception NoSuchElementException if user attempts to access empty list element
* #exception ArithmeticException if user attempts to divide by 0
* #exception ArrayIndexOutOfBoundsException if user supplied less than 3 arguments
* #exception IOException problems with creating and writing files
* #exception RuntimeException if user attempts to pass empty list to constructor
*/
public static void main(String[] args) {
try{
//some code
} catch (NoSuchElementException e) {
System.out.println("Accessing element that does not exist: " + e.toString());
} catch (ArithmeticException e) {
System.out.println("Division by zero: " + e.toString());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please supply a command line arguement that specifies your file path: " + e.toString());
} catch (IOException e) {
System.out.println("Other IO errors: " + e.toString());
} catch (RuntimeException e) {
System.out.println(e.toString());
}
}
}
I would like to know if there is any better and cleaner way to catch multiple exceptions.
First, unless you have very good reason, never catch RuntimeException, Exception or Throwable. These will catch most anything that is thrown, and Throwable will catch everything, even those things you're not meant to catch, like OutOfMemoryError.
Second, avoid catching runtime exceptions unless it directly impedes with the critical operation of your program. (But seriously, if anyone sees you catch a NullPointerException, they are within their full rights to call you out on it.) The only exceptions you should be bothering with are those that you are required to handle. Out of your list of exceptions, the only one you should bother with is IOException. The rest are the result of not enough tests, or sloppy coding; those shouldn't occur in the normal run time of your application.
Third, in Java 7, you have the ability to do a multi-catch statement for your exceptions, if the exceptions are mutually exclusive. The example linked does a good job of explaining it, but if you were to encounter code that threw both an IOException and an SQLException, you could handle it like this:
try {
// Dodgy database code here
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
This cleans things up a bit, as you don't have unwieldy and huge chains of exceptions to catch.
First of all the problem with "best practice" advice is that it tends to over-simplify the question and the answer. Then someone (like yourself) comes along and notices that it is contradictory1.
IMO, best practice is to take "best practice" advice and people who regularly use that phrase with a healthy level of suspicion. Try to understand the real issues yourself, and reach your own conclusions ... rather than just relying someone else to tell you what is "best practice".
1 - Or worse ... they don't notice the contradictions, edge-cases, etc, and blindly follow the so-called "best practice". And occasionally, they find themselves in a dark place, because the "best practice" recommendation was inappropriate.
So what's the problem here? It is this statement:
but I also heard that catching generic exception is not a good coding practice.
In fact, it is not normally good coding practice to catch generic exceptions like Exception. But it is the right thing to do in some circumstances. And your example is one where it is appropriate.
Why?
Well lets look a case where catching Exception is a bad idea:
public void doSomething(...) {
try {
doSomethingElse(...);
} catch (Exception ex) {
// log it ... and continue
}
}
Why is that a bad idea? Because that catch is going to catch and handle unexpected exceptions; i.e. exceptions that you (the developer) did not think were possible, or that you did not even consider. That's OK ... but then the code logs the exception, and continues running as if nothing happened.
That's the real problem ... attempting to recover from an unexpected exception.
The (so-called) "best practice" advice to "never catch generic exceptions" deals with the issue, but in a crude way that doesn't deal with the edge cases. One of the edge cases is that catching (and logging) a generic exception is OK if you then immediately shut the application down ... like you are doing.
public void main(...) {
try {
// ...
} catch (Exception ex) {
// log exception
System.err.println("Fatal error; see log file");
System.exit(1);
}
}
Now contrast that with the (supposedly) good practice version in your question. What is the difference?
Your version produces more user friendly / less alarming diagnostics ... up to a point.
Your version is significantly more code.
Your version is unhelpful to someone trying to diagnose the problem because the stacktraces are not recorded.
And the counterpoints to 1 and 2 are:
You can spend limitless time honing the "user friendly" diagnostics for an application, and still fail to help the kind of user who can't or won't understand ...
It also depends on who the typical user is.
As you can see, this is far more nuanced than "catching generic exceptions is bad practice".
I have just been thinking about this, as it is possible but I want to know if it is considered "bad practice". I believe it is, but I want to ask for views on it to check my opinion.
Is it bad to do something like this:
try{
something();
somethingelse();
try{
foo();
bar();
}catch(Exception e){
e.printStackTrace();
}
somethingelseagain();
}catch(Exception e){
e.printStackTrace();
}
I think there should never be a need to do this, since anything that throws an exception would trigger the first catch anyway.
Views are greatly appreciated.
In your example, as written, the inner catch is a bit redundant.
However, nested catches would have more use in circumstances such as:
catching different exceptions
doing something different in the handler block for the two catches
inner catch might catch the exception, do something, then re-throw the same exception which the out catch block could catch
Also, don't forget the potential use of the finally block, which can execute cleanup code even if an exception was caught.
You should generally try to catch the most explicitly typed (i.e. specific) exception(s) as possible.
The subject of exceptions is an interesting one, and not without controversy.
A case that I think you might want to nest try statements is if you request user input in your catch and that input might be invalid.
Nested try-catch is fully justified when circumstances call for it. For example, you don't want to skip any steps and break out of the main try if a certain method throws a certain exception. If it throws any other exception, then you want the normal behavior.
This is on Java 6
Can I have a common method to handle my exceptions - so instead of doing this n times in each method
try {
// Do something
} catch (XException e) {
// Do something
} catch (YException e) {
// Do something
} catch (ZException e) {
// Do something
}
I have
try {
// Do something
} catch (Exception e) {
handleAll (e);
}
and method handleAll(e) does
if e.instanceOf(XException)
else if e.instanceOf(YException)
else if e.instanceOf(ZException)
Is there anything wrong with the 2nd approach?
Update:
My original question was about "centralizing the handling" in one place for both checked and runtime exceptions. The answers have pointed out I should avoid instanceof().
#aioobe's idea looks very neat to me. Are there any negative opinions on that approach?
There is one minor problem as I see it. Since you really want the handleAll method to rethrow any uncaught exception, it has to be declared throws Exception. This means that so does the methods that call handleAll.
If X-, Y- and ZException are all RuntimeExceptions I see nothing wrong with this. (I may have overlooked something though, as this is the first time I've seen this approach.)
To be sure that the instanceof approach behaves exactly as the catch clauses would, I would consider designing the handleAll(RuntimeException e) like this though:
private void handleAll(RuntimeException e) {
try {
throw e;
} catch (XException xe) {
...
} catch (YException xe) {
...
} catch (ZException xe) {
...
}
}
It's a BAD approach. It will reduce LOC (Line Of Code) but it will create difficult to understand, More resource dependent (It requires more memory and processing capacity). it also reduce Readability.
So first one is the best one
You can do this, but I don't think it's good coding style. It's convenient to keep exception handlers close to the lines that throw the Exceptions.
Suppose your code changes, and throws a new Exception. Then you have to update the method that handles them; so now you have to make changes in two places. Same happens if a particular Exception is no longer thrown by the code, or if you decide that some Exceptions should be handled at a higher level.
Also, I'm wary of "catch (Exception exc)". It's too general, try to make your Exception handlers as specific as possible.
Java 7 will make things better. Because catching multiple exceptions is possible.
There is something really wrong with the second approach: if the called method signature is modified and throws a new kind of exception, the code will still compile fine, whereas you have not handled this new exception correctly.
Using the first approach, the compiler will produce an error, which will force you to handle the new exception.
The second approach will catch all Exceptions, including RunTimeExceptions. Make sure you handle them correctly.
I think every exception is unique (when compararized place in code, not the time when exception is thrown) so you should not generilaze exception handling.
You might want to handle exception little difference each time IE. if some where is thrown FileNotFoundException you might create a new file but other time that might be fatal Exception that causes applications termination.
Is it considered bad practice to have multiple try's in one method and structure the code like this?
public void whatever() {
try {
methodThatMayThrowIOException();
} catch(IOException io) {
// do something with exception here
}
// do more stuff here that won't throw exceptions
try {
methodThatMayThrowCustomException();
} catch(CustomException ce) {
// do something with custom exception here
}
}
If the method can continue execution, without any problems even if the specified exception occurs this should be fine.
In the event where the exception should cause problems further down the line in the method, I would have it bubble up.
No it's not. It is a good point to catch specific exceptions when they might be thrown, imho it is surely better than this:
public void whatever {
try {
methodThatMayThrowIOException();
// do more stuff here that won't throw exceptions
methodThatMayThrowCustomException();
} catch(ParentException e) {
// do something with custom exception here
}
}
Your code reads like it does because you want to do part 1 (and resolve, catching IOException if necessary), do the no-exceptions part, and then do the methodThatMayThrowCustomException. Your code can literally not be written any other way and retain the same functionality. That's an exaggeration, but any other version would be different in a superficial sense.
This is not the same:
public void whatever {
try {
methodThatMayThrowIOException();
// do more stuff here that won't throw exceptions
methodThatMayThrowCustomException();
} catch(IOException io) {
// do something with io exception here
} catch(CustomException ce) {
// do something with custom exception here
}
}
and the way it would execute if any of the Exceptions are thrown is quite different. If you need to sequentially recover from Part 1, hit Part 2 in any case, then carry on to Part 3, you cannot really write your code any other way.
There's nothing wrong with having two catch blocks, though mixing something that causes an IOException with something that throws a CustomException might suggest a mixing of concerns, making your code hard to understand. But as it is, it's not just valid, it's the only way to do what you're doing.
Looks OK but it depends on what methodThatMayThrowIOException and methodThatMayThrowCustomException do and whether failure of the first one (methodThatMayThrowIOException) should fail the whole whatever method.
It really depends on what you plan to do if an IOException thrown. Your style allows you to do more things, but if you're not actually planning to take advantage of that, then that intention is made much clearer by using the standard idiom.
public void whatever {
try {
methodThatMayThrowIOException();
// do more stuff here that won't throw exceptions
methodThatMayThrowCustomException();
} catch(IOException io) {
// do something with io exception here
} catch(CustomException ce) {
// do something with custom exception here
}
}
Here you can tell quickly that if IOException is thrown, then you only do what's inside the catch block and not much else.
I don't see why that would be bad practice, as long as you actually do something useful with the exceptions you caught.
There is no problem with this, AFAICS. However, 2 try-catch in a method stabs in my eyes. If you feel the same, I suggest you to refactor it in a proper way.
No. That's a pretty good practice to narrow down the scope where some kind of exceptions are thrown. I did this a lot in my code.
However, if you are sure that in one try...catch block, certain kind of Exception will only be thrown by a unique function, putting them in the same try block is also OK.
well it depends on what you are trying to accomplish. you would normally enclose a block of code in a single try-catch block if the code block should be executed as a block or not at all if some exception occurs. if it's not the case, then i believe it is much better to isolate the different code blocks throwing different exceptions into different try-catch blocks sandwitching "do more stuff here that does not throw exception". just a thought!
Personally, I think it looks cluttered. I prefer to have just one try, with as many catch blocks as I need. I don't care or multiple try/catch sequences in a single method.