exception handling and finally block in java - java

public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
try {
a[0] = 4;
if (i <= 0) {
int k = j / i;
} else {
System.out.println(j / i);
}
} catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
void k() {
int[] a = new int[2];
{
try {
a[4] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range");
}
}
}
}
public class Nested {
public static void main(String[] args) {
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}
}
Output:
-2
Executing finally block in code
Wrong valuejava.lang.ArithmeticException: / by zero
Executing finally block in code
out of range
out of range
Whenever i am executing the finally{} block written in the code below it is getting executed twice. Don't know why this is happening. I want to run the finally block only once.
Is there any way to throw multiple exception in single method?

It because you have two Confusion objects. Therefore, the constructor will be executed twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);

confusion c=new confusion(2);
confusion c1=new confusion(0);
thats why u are getting 2 outputs from finally.

This is because you are creating two objects c1 and c

The finally block always executes when the try block exits.
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
So regardless of any exception it will execute finally block. As you create two objects, it will call the constructor twice and will also execute finally twice.

You are calling the code in the try twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);
This means that as the finally happens every time the try is called, it'll print...
Executing finally block in code
If you called it again,
confusion c1=new confusion(3);
It'd print out the contents of the finally a third time.

You are creating two objects using following code. Thats why the finally block is executed two times.
confusion c=new confusion(2);
confusion c1=new confusion(0);
Try this one please
public static void main(String[] args){
confusion c=new confusion(2);
confusion c1=new confusion(0);
confusion c1=new confusion(10);
confusion c1=new confusion(5);
}
Now finally block called 4 times.
Constructor in Java is block of code which is executed at the time of Object creation.
Please read constructor reference http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Because you are creating two Confusion objects. Therefore, the finally block will be executed twice.
confusion c=new confusion(2);
confusion c1=new confusion(0);
If you want to execute finally only once.Try this code
public class Confusion {
Confusion(int i) {
int j = 5;
int[] a = new int[2];
a[0] = 4;
if (i <= 0) {
int k = j / i;
} else {
System.out.println(j / i);
}
}
void k() {
int[] a = new int[2];
a[4] = 4;
}
}
public class Nested {
public static void main(String[] args) {
try{
Confusion c = new Confusion(2);
Confusion c1 = new Confusion(0);
c1.k();
c.k();
}catch (ArithmeticException sa) {
System.out.println("Wrong value" + sa);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of range massage in Class");
} finally {
System.out.println("Executing finally block in code");
}
}
}

Related

Finally block excecution

When the below method is called it's printing output as 6 but I am expecting output as 5 as I have re-assigned n = 5 in the finally block.
Can anybody please help me with this?
public static int p() {
int n = 0;
try {
n = 6 ;
return n;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
}
This can easily be answered by understanding the order of execution of your code. In your scenario you will always be returning the value of n before you hit the final block, in your code you will always be returning the value of 6. You will never return 5 (Final Block) or 0 (Catch Block).
So why would you never get 0?
You would never get 0 because the code within the try part of your try-catch-final statement will never in a million years throw any exception the way it has been written, so the catch statement is redundant.
So why would you never get 5?
You would never get 5 because the order of execution is return statement in the try block is executed first and then the final block runs. A try-final statement is the only statement I can think of (Happy to be proven wrong in comments) that any code is executed after a return statement is executed.
There is no reason why in your scenario you would have that final block unless for whatever reason you didn't trust the Garbage Collector was doing it's job, in which case you would nullify the n property here and that's it.
Your code could easily be re-written as the below because 6 is the only value your code will ever return.
public static int p() {
return 6;
}
As mentioned by luk2302 you are already return the value as 6. If you want to return the value as 5 then change your method as shown below.
public static int p() {
int n = 0;
try {
n = 6;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
return n;
}
Question is very interesting, i even surprised why it is happening like that. When i checked about finally block i got the definition like below
"Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not."
But i have compiled your program and saw how the compiled class looks like. It gives the answer
Original Java class
public class Finally {
public static int p() {
int n = 0;
try {
n = 6 ;
return n;
} catch (Exception e) {
return n;
} finally {
n = 5;
}
}
public static void main(String[] args) {
int n = p();
System.out.println("value of n " + n);
}
}
Compiled class
public class Finally {
public Finally() {
}
public static int p() {
byte n = 0;
byte var2;
try {
n = 6;
byte var1 = n;
return var1;
} catch (Exception var6) {
var2 = n;
} finally {
boolean var8 = true;
}
return var2;
}
public static void main(String[] args) {
int n = p();
System.out.println("value of n " + n);
}
}
As you can see how return statements translated due to that we don't see the value which is assigned in finally block instead we see value which is assigned in the try block.
Hope that clarify your answer.

The order of return value with try catch finally

I use this code to test try catch finally:
public class My{
public static void main(String[] args) {
System.out.println(fun1());
System.out.println(fun2());
}
public static int fun1() {
int a = 1;
try {
System.out.println(a / 0);
a = 2;
} catch (ArithmeticException e) {
a = 3;
return a;
} finally {
a = 4;
}
return a;
}
public static int fun2() {
int a = 1;
try {
System.out.println(a / 0);
a = 2;
} catch (ArithmeticException e) {
a = 3;
return a;
} finally {
a = 4;
return a;
}
}
}
output:
3
4
I know that finally will always run. I think the result of the two functions should be 4, but actually fun1() is 3 and the fun2() is 4. Why?
This question is closely related, although it returns literals but not variables: Multiple returns: Which one sets the final return value?
In fun1 the return value is set via return a in the catch-block. At that line the value of a is copied into the return value. Changing a later does not change the return value.
In fun2 you have an explicit return in the finally block, so the return value in the finally block is what is returned.
Please read carefully through the answers in the question above for why you should not write code like that.
Another related question is this one: Returning from a finally block in Java
In simple words when a function returns something it returns from the last executed return statement. in fun2() first return value is 3 which gets overridden by finally block's return value i.e 4. Whereas in fun1() method return is set to 3 from catch block and since the last line of func1() never gets executed hence 3 is returned.

When does try-with-resources close the resource?

I'm preparing myself for fall exam in Object Oriented Programming and one type of tasks we are given is providing output from code which usually consists of some Exception handling problems.
Now my question is when does try-with-resources close it's resource because my output is strictly dependent on output from class that implements AutoCloseable.
In provided code, what I don't understand why "close 1" output comes before "close 40", or why is object A(40) closed at the end of this block. Is it because A(50) is same type as A(40)?
My main question when does the AutoCloseable close the given resource, like in example m1 when i=1:
1) A(1) is created
1b) Try block is executed
2) A(1) is closed
3) ArrayIndexOutOfBoundsException is handled?
public class Main {
public static void main(String[] args) {
int[] arr = new int[] { 15, 10 };
for(int i=1; i>=-1; i--){
try(A a40 = new A(40)) {
m1(arr, i);
A a50 = new A(50);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("array exc");
}
catch(Exception e) {
System.out.println("main exc");
break;
}
finally {
System.out.println("main finally");
}
}
System.out.println("main done");
}
private static void m1(int[] arr, int i) throws Exception {
try(A a1 = new A(i)) {
m2(arr[i] + arr[i+1], i);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("m1 exc");
}
System.out.println("m1 done");
}
private static int m2(int x, int y) {
int r = 0;
try{
A a2 = new A(x+y);
r = x / y;
}
finally {
System.out.println("m2 finally");
}
System.out.println("m2 done");
return r;
}
}
And class A which implements AutoCloseable:
public class A implements AutoCloseable {
private int x;
public A(int x){
this.x = x;
System.out.println("A " + x);
}
#Override
public void close() throws Exception {
System.out.println("close " + x);
}
}
Here is output of provided code:
A 40
A 1
close 1
m1 exc
m1 done
A 50
close 40
main finally
A 40
A 0
A 25
m2 finally
close 0
close 40
main exc
main finally
main done
The specification is pretty clear on this.
14.20.3. try-with-resources
A try-with-resources statement is parameterized with local variables (known as resources) that are initialized before execution
of the try block and closed automatically, in the reverse order from
which they were initialized, after execution of the try block.
Your example is a bit convoluted. Try to simplify it. There are two scenarios you are interested in: an exception thrown in the try block, an exception isn't thrown in the try block. You debugging messages is informative, so you will be able to track the flow easily.
You may want to look into decompiled .classes to see what actually was generated.

Java: handle exception and return result from inner method

Question: How to do both: handle exception in outer method and return result of inner method?
I have: two methods which return List:
import java.util.List;
import java.util.LinkedList;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Result = " + new HelloWorld().parseWrapper());
}
public List<Integer> inner() {
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 5; i++) {
if (i % 4 == 0) throw new RuntimeException();
list.add(i);
}
return list;
}
public List<Integer> outer() {
List<Integer> list = null;
try {
list = parse();
} catch (Exception e) {
System.out.println("Handle exception!");
} finally {
return list;
}
}
}
Result:
Handle exception!
Result = null // PROBLEM: I DON'T WANT TO LOOSE IT
Problem: I loose result list. I want both: to handle exception and to return [1, 2, 3] list from outer method.
No - the inner method doesn't return anything, because it throws an exception instead. The outer method simply doesn't have a result to work with.
If a method throws an exception, it's generally expected that none of the work in the method is useful.
If you want to populate a list as far as you can, you could pass the list into the method instead:
public void inner(List<Integer> list) {
for (int i = 0; i < 5; i++) {
if (i % 4 == 0) throw new RuntimeException();
list.add(i);
}
}
Then call it as:
public List<Integer> outer() {
List<Integer> list = new LinkedList<>;
try {
parse(list);
} catch (Exception e) {
System.out.println("Handle exception!");
} finally {
return list;
}
}
It's rarely a good idea, to be honest - in my experience, most exceptions can't really be handled and resumed; it's more a case of "work out what needs to be cleaned up, and the unit of work to abort". That's not universally true of course, but what you're trying to achieve in terms of partial results from a method is pretty rarely useful.
You could just bring your list instanciation at the class level:
public class HelloWorld {
private List<Integer> list = new LinkedList<>();
public List<Integer> inner() {
for (int i = 0; i < 5; i++) {
if (i % 4 == 0) throw new RuntimeException();
list.add(i);
}
return list;
}
public List<Integer> outer() {
try {
parse();
} catch (Exception e) {
System.out.println("Handle exception!");
} finally {
return list;
}
}
}
Just be careful with multiple accesses to the same instance of your class, as you will be messing with same list instance in each call.
But still I'm wondering the real reason of throwing an exception there instead of just returning the partial list:
if (i % 4 == 0) return list;

Cannot Run the below program of try and catch

public class exdemo1 {
public static void main(String args[]) {
int a = 10, b = 0, ans;
int arr[] = {10, 20, 30};
try {
ans = a / b;
System.out.println("Division" + ans);
System.out.println("4th Element" + arr[3]);
} catch (ArithmeticException ae) ;
{
System.out.println(ae);
}
catch (ArrayindexoutofboundsException ae) {
System.out.println(ae);
}
}
}
Now that your code is properly formatted, you will probably notice an extra ; after the first catch block.
I do not know what you mean exactly by that, but these are the issues I am noticing:
Your array does not have a 4th element, it has 3 elements, the last of which can be accessed through arr[2]
You can't divide by 0.
catch (ArithmeticException ae) ; You must remove the ; at the end of the line, you do not need that there.
ArrayindexoutofboundsException The proper class is ArrayIndexOutOfBoundsException.
I am assuming you know about the first two due to the catch statements.
Fixing those should make your program compile.
It is ArrayIndexOutOfBoundsException and not ArrayindexoutofboundsException
You have an extra semicolon after your first catch. Remove that. Also, I do not think ArrayindexoutofboundsException is a valid exception, should be ArrayIndexOutOfBoundsException?
You have mixed two programs together but only one Exception will be thrown. You program does basically the same thing as
public static void main(String... args) {
int a = 10, b = 0;
int ans = a / b;
}
This will print the exception thrown.

Categories