I recently came across code written by a fellow programmer in which he had a try-catch statement inside a catch!
Please forgive my inability to paste the actual code, but what he did was something similar to this:
try
{
//ABC Operation
}
catch (ArgumentException ae)
{
try
{
//XYZ Operation
}
catch (IndexOutOfRangeException ioe)
{
//Something
}
}
I personally feel that it is some of the poorest code I have ever seen!
On a scale of 1 to 10, how soon do you think I should go and give him a piece of my mind, or am I over-reacting?
EDIT:
What he is actually doing in the catch, he is performing some operations which can/should be done when the initial try fails. My problem is with having a clean code and maintainability. Delegating the exception from the first catch to a different function or the calling function would be OK, but adding more code which may or may not throw an exception into the first catch, is what I felt was not good. I try to avoid multiple stacked "if-loop" statements, I found this equally bad.
Why is that bad? It's no different conceptually than:
void TrySomething() {
try {
} catch (ArgumentException) {
HandleTrySomethingFailure();
}
}
void HandleTrySomethingFailure() {
try {
} catch (IndexOutOfRangeException) {
}
}
Before you go over there and give him a piece of your brain (try the parietal lobe, it's particularly offensive) , what exactly are you going to say to him? How will you answer the proverbial "why?"
What's even more ironic is that when the jitter inlines this code, it will look exactly like your example.
-Oisin
Here is a case :
try{
//Dangerous Operation
} catch (AnyException ae) {
try {
//Do rollback which can fail
} catch (RollbackFailedException rfe) {
//Log that
}
} finally {
try {
//close connection but it may fail too
} catch (IOException ioe) {
//Log that
}
}
It's about the same thing as #x0n said. You might need to handle exception while try to close resources or while you're trying to resolve a situation brought by another exception.
Without knowing what the code does it's impossible to say. But it's not unusual to do this.
e.g. if you have to clear up resources whilst handling exceptions, that clear-up code itself may have the capability to throw exceptions.
Related
I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}
I have 2 examples:
void terminate(String x) {
System.exit(0);
}
void x (long y) {
if(y == null) {
terminate();
}
//code
}
.....
x(null); //Don't want that
This example seems to work. I want to make sure that long y is not null. I might do this instead:
void x (long y) throws NullPointerException {
//code
}
...
try {
x(null);
} catch (NullPointerException e) {
e.printstacktrace();
}
What would the difference in performance be? In such example, it might not be visible, but in a complex program, would it matter? Should I get into practice of exceptions instead of if then?
Use exceptions for exceptional circumstances, when things happen that youdid not expect and where nothing sensible can be done to recover.
Otherwise, use if-then and maybe return a status code.
In terms of performance, exceptions create a huge overhead compared to returns. Calling a method and catching an exception if it didn't work is verbose and annoying.
void myOperation() {
step1();
step2();
step3();
}
In this example, exceptions are preferable for when any of the steps fails, the entire operation fails anyways, so I prefer not having to deal with any of this.
void myOperation(String number) {
int n;
try {
n = Integer.parse(number);
} catch (NumberFormatException e) {
n = DEFAULT;
}
doThings(n);
}
In this case, having to catch the exception is annoying because I kind of expect the string to be invalid and have a reasonable alternative. The exception makes the code slow and verbose.
What would the difference in performance be?
Version with exception definitely will works slower and will have overhead of processing exceptions, creating objects, filling stack traces and so on.
In such example, it might not be visible, but in a complex program,
would it matter? Should I get into practice of exceptions instead of if then?
In complex programs none use this kind of processing possible null pointer exceptions, and it's actually anti-pattern in java, so if you whant be save with null you should you kind of not null check like if(x!=null) or assert.
Also I advice you read more about exceptions in java and differences between checked/unchecked exceptions and so on.
PS here is good topic about null checks.
I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it:
public response newStuff(//random data inside) {
try {
response or = //gives it a value
log.info(or.toString());
return or;
}
catch ( Exception e) {
e.printStackTrace();
}
finally {
return null;
}
}
Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
Is there really any point in adding a finally block here?
The answer to this is a resounding "no": putting a return statement in the finally block is a very bad idea.
I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null unconditionally the way the original code does, the code with the return inside the catch block would return null only on errors. In other words, the value returned in the try branch would be returned to the caller unless there is an exception.
Moreover, if you add return null after the catch block, you would see the correct effect of returning null on exception. I would go even further, and put a single return in the method, like this:
response or = null;
try {
or = //gives it a value
log.info(or.toString());
} catch ( Exception e) {
e.printStackTrace();
}
return or;
Actually, no. Finally is (nearly) always run, no matter what the result in the try-catch block; so this block always returns null. Here, look at this example:
public class Finally {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(finallyTester(true));
System.out.println(finallyTester(false));
}
public static String finallyTester(boolean succeed) {
try {
if(succeed) {
return "a";
} else {
throw new Exception("b");
}
} catch(Exception e) {
return "b";
} finally {
return "c";
}
}
}
It will print "c" both times.
The above mentioned exception to the rule would be if the thread itself is interrupted; e.g. by System.exit(). This is however a rare thing to happen.
The finally is always executed no matter what, and normally can be used to close sessions, etc.
Don't put returns inside a finally block.
This looks like a very bad practice. In this case your code will always return null.
The finally block is called last after the try-catch block runs. No matter if the try finished or the exception block was called. In this case, no matter which path of code is ran, you will always return null.
In the "normal" case where you put the return null after the finally there's indeed a chance to return something (either from the try or from the catch block) and if no flow yields a return object, you fall back to the return null, but you don't always return null.
I've read that a lot of people simply answer "don't use return in a finally block", without any explanation. Well, actually the code you posted is a good example where a return in a finally block is causing massive confusion. Even the, as of time of writing this, most upvoted answer, got it wrong. Your code will always execute the return null; as last command, even if there is an Exception.
But I can think of a situation where a return in a finally block actually makes sense. It appears to me that the goal of the author of your code was that the method never throws a Throwable, but returns null instead. This can actually be achieved if you modify the code like this:
public Result newStuff() {
Result res = null;
try {
res = someMethod();
log.info(res.toString());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
return res;
}
}
But note that this will not call printStackTrace() on Errors and Throwables which are not Exceptions.
The "Finally" block will execute regardless of whether the "Catch" fires or not. So the behaviour is different than if you just put "return null" in the Catch block.
There should be no return statement in the finally block,remove return.
The need of finally block is where when you have such a code that should always be executed like you want to close your input stream or you want to close any connection etc.Just googled about this you will easily find the example for this.
In your case you are writing a method where you are returning something in try block and at the end you are writing finally block where you are returning null.I don't see any use of finally block here.
Finally block is used if you want to execute some statements even if code in try block or catch block generates an exception or not. But as you are using return in try block then there is no significance of putting a return in finally block. You can return directly from catch block and can remove finally block.
First understand why we need this three blocks in simple words for beginners.
1)try block: If you have doubt that your code will lead to an exception then put in try block
2)catch block: If exception arises then a piece of code you need to perform should be written in this block
3)finally block: If you want your piece of code to be executed no matters if exception arises or not then we go for finally block. Mainly this block is use for releasing resources.
For example:
try{
Connection conn=//something;
//some code for database operations
}catch(SQLException e){
e.printStackTrace()
}finally{
conn=null;
}
No matter what is result, you have to make connection as null because it is heavy object which if referenced will create load on database as only few connection objects are available.
Hence best way to keep them in finally block.
In your case, return null in finally block is bad approach as it will always return null although exception arises or not.
I know that there are ways to know the cost of cycle or an iteration statement, but I want to know 2 things:
1st.
Which of these two listing is more cost effective? (or if there are a better approach, I'm all ears):
UPDATE: The question then goes: Wich of the 2 of them will do proper use of the memory/GC?
Keep in mind that, the "values" of reqObj and resObj are not going to be necessary for the next loop.
for (TransactionLog transactionLog : transactionLogList) {
RequestObj reqObj = new RequestObj();
ResponseObj resObj;
try {
//do things with these 2 babes and the transactionLog
} catch (WhateverException ex) {
log.error("Error in XYZ while doing whatever", ex);
//execute code without throwing anything up
} finally {
reqObj = null;
resObj = null;
}
}
or
RequestObj reqObj = new RequestObj();
ResponseObj resObj;
for (TransactionLog transactionLog : transactionLogList) {
try {
//do things with these 2 babes and the transactionLog
} catch (WhateverException ex) {
log.error("Error in XYZ while doing whatever", ex);
//execute code without throwing anything up
} finally {
//do something
}
}
and 2nd.
Where I can find a good place/book/site to learn this "algorithms best practice" and the function O(letter) to calculate the interation's statement cost?
PD: Sorry for my English... he's not very good looking. xD
Local objects is clearer, less error prone, and such objects get handled well by the garbage collector. For reusable objects like a StringBuilder you could clear in every cycle instead of doing new StringBuilder I was surprised it holds too (said someone).
Just as setting to null is a beginner's signature.
If RequestObj and ResponseObj are AutoCloseable (or you implement them as such), then you should consider using the try-with-resources block available with Java 7. It takes care of any cleanup that they require, or that you want, without the extra finally (or an additional catch in the finally, for that matter; those exceptions are suppressed).
try( RequestObj reqObj = new RequestObj(); ResponseObj resObj = ... ) {
// Do stuff
} catch (WhateverException ex) {
log.error("Error in XYZ while doing whatever", ex);
// execute code without throwing anything up
}
// No finally block required
You shouldn't worry about the GC/Memory issues as much as that seems to be premature optimization in your case. It's better to keep your code clean and readable.
For more information: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
i was asked a question in interview what happens if we put finally block between try and catch block i answered in that case compiler will think that there is no catch block and it will directly execute finally block.
Then he asked why is it not possible to put code between try and catch block?
Can you please help me...
Okay, first thing first - the compiler doesn't execute the code, it just compiles it, allowing it to be run by the JVM.
Empirically speaking, that wouldn't make too much sense, since if you have some code that you would want to put outside the try block but before the catch block, the code could just as well be placed in the try block. The thing is, it would just behave as it were in the try block anyway if you think about it.
Let's assume this is valid Java (this doesn't compile):
try {
throw new Exception();
}
System.out.println("Sup!");
catch(Exception e) { }
When the exception gets thrown, that line that prints out Sup! will still get skipped as the JVM is searching to jump to the appropriate exception handler to treat Exception. So, in a way, the code behaves just as it would if it were in the try {} block itself, which is why it wouldn't really matter where it is, and the Java specifies that this (now proven useless) construct is illegal.
Now what if that code after the try were to throw another exception itself? If it were valid code, it would behave just like a nested try...catch block in the original try block. Of course that once things start getting complicated, the approach where there is no clear connection between a try and a catch block could get fuzzy, and the JVM would end up not knowing which catch/finally belongs to which try block (especially since the handler doesn't have to be in the same function, or even in the same package!).
Well, the flippant answer is that the language spec forbids it.
But let's step back a bit and think about it a different way - what if you could do this?
try {
foo();
}
bar();
catch (Exception e) {
baz();
}
What could the semantics of this be? If we catch an exception in foo(), is baz() called? What about bar()? If bar() throws, do we catch the exception in that case?
If exceptions in bar() are not caught, and exception in foo() prevent bar() from running, then the construct is equivalent to:
try {
foo();
} catch (Exception e) {
baz();
}
bar();
If exceptions in bar() are caught, and exception in foo() prevent bar() from running, then the construct is equivalent to:
try {
foo();
bar();
} catch (Exception e) {
baz();
}
If exceptions in bar() are not caught, and exception in foo() do not prevent bar() from running (bar() is always executed), then the construct is equivalent to:
try {
foo();
} catch (Exception e) {
baz();
} finally {
bar();
}
As you can see, any reasonable semantics for this between-try-catch construct are already expressible without the need for a new - and rather confusing - construct. It's hard to devise a meaning for this construct that is not already redundant.
As an aside, one potential reason we can't do:
try {
foo();
} finally {
bar();
} catch (Exception e) {
baz();
}
could be that it does not reflect actual execution order - catch blocks run before the finally block. This allows catch blocks to make use of resources that the finally block might release later (for example, to request additional diagnostic information from a RPC object or something). Could be made to work the other way as well? Sure. Is it worth it? Probably not.
Well it would mean something like this :
try
{
somCode();
}
someMoreCode();
catch
{
}
What should this mean ?
This is not possible because it has no semantic, and therefore it has been decided to be syntaxically incorrect by language designers!
If you have a try you must have either catch or finally, as defined in the java language specification, 14.20 "The try Statement`
try and catch like .. if and else ..
so there is no need to add code between try and catch block