Catch Finally Block [duplicate] - java

This question already has answers here:
Try-catch-finally-return clarification [duplicate]
(2 answers)
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 5 years ago.
Hi I have a question about catch and finally.
I looked around for the same case but had no luck but I'm sure this has been asked before.. so this may be a duplicate. Sorry for that.
Anyway this is my question:
Here is a method which returns a boolean
public static boolean runtimeException() {
try {
int i = 1 / 0;
} catch (ArithmeticException ae) {
return true;
} finally {
return false;
}
}
When I call this method in my main function:
public static void main(String[] args) {
boolean flag = runtimeException();
System.out.println(flag);
}
The result is: "false".
Id like to know why this happens.
I know that the finally block has to be executed at any means but logically the results don't make sense to me because the catch block is executed before and the function has already returned true. How can the function return false after already returning true??
Thanks in advance.

Related

Why value from inside of "try" is printed during catching the exception? [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 5 years ago.
I have code like this:
class ExceptionTest{
public Integer divide(int a, int b) {
try {
return a/b;
}finally {
System.out.println("Finally");
}
}
}
public class Three {
public static void main(String[] args) {
ExceptionTest test = new ExceptionTest();
try {
System.out.println(test.divide(10, 0));
}catch(Exception e) {
System.out.println("DIVIDED BY 0!");
}
}
}
When I run the code it prints:
Finally
DIVIDED BY 0!
Why is that? If there Exception has been caught shouldn't only "DIVIDED BY 0!" be printed?
EDIT:
I know that finally is always printed, but what I mean is that try-finally in the method called "divide" is called in try-catched block in main. So If exception is being caught why something from try in try-catch is printed? Even if my ExceptionTest class looks like this:
class ExceptionTest{
public Integer divide(int a, int b) {
System.out.println("Finally")
return a/b;
}
}
So there is no try-finally block and exception is being thrown and I still have
Finally
Divided by 0!
The Docs tell us about the finally-block
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
So even if you divide by 0, which raises an Exception, the finally block will be reached.
The code within the finally block is always run, even if the code executes correctly. You need to use catch instead, which is only executed when an error occurs.
try { /* Runs first, and stops executing if an Exception's thrown. */ }
catch(Exception e) { /* Run whenever an Exception's thrown. */ }
finally { /* Always runs. */ }
You also need to make sure that you return a value from the catch clause. Something like
try {
return a / b;
} catch (ArithmeticException ae) {
System.err.println("Cannot divide by zero!");
return -1;
}

Does a return statement end a method? [duplicate]

This question already has answers here:
Does "return" stop the execution of a method?
(6 answers)
Closed 5 years ago.
Let's say I have a method, for instance, the one I'm working on is a boolean Empty method, that simply returns false if the list (technically it's a stack using linked lists) is empty, and returns true if it has values.
I have an if statement that returns false if the first value of the list is null (considering it's a stack) and returns true if it has values.
Here is that method in my code:
public boolean empty(){
if(list.getFirst() == null){
return false;
}
else{
System.out.println("Stack has values.");
}
return true;
}
my question is, if I have determined that the list is empty and return false, will the method end there? Or, in other words, does a method stop doing things once it gets a return message?
A method mostly stops doing things once you hit a return statement. One exception is that if you have a try block with a finally clause, that finally clause will be executed.
It just exits the method at that point. Once the return is executed, the rest of the code in the method won't be executed and control will be passed to the parent.
eg.
public boolean test(int n) {
if (n == 1) {
return true;
}
else if (n == 2) {
doStuff();
return false;
}
doOtherStuff();
}
Note that the compiler is smart enough to tell you some code cannot be reached:
if (n == 3) {
return;
customFunction(); //compiler error here
}

Check if a String is Integer [duplicate]

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 7 years ago.
I need to check whether the String is an Integer. And I found such solution:
private boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Is there a more beautiful and proper way to do this without try/catch clause?
You can try a regex like:
Code
private boolean isInteger(String str) {
return str.matches("\\-?\\d+");
}
Edit
Thanks #Maloubobola for noting that my first attempt would not parse signed integers.
You can try regex. Here is one for positive and negative numbers
private boolean isInt(String string) {
return string.matches("-?\\d+");
}

catch Exception with add [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I wrote this statement in the main method
the Exception will be in the (GuaranteeYears) so i put it in the try block.
First in the main I make a Store object and pass number 4 in parameter, in the Store class I will have a array called arrProduct that will have the length 4:
boolean flag1 = true;
while (flag1) {
try {
System.out.println("Ente GuaranteeYears");
int GuaranteeYears=read.nextInt();
StrongDevice s = new StrongDevice(code,type,price,Model,Capacity,GuaranteeYears); //the object
flag1 = false;
x.addProduct(s);
}
and this is my add method
public boolean addProduct(Product p) {
if(arrProduct.length==NumOfProduct)
return false;
arrProduct[NumOfProduct]=p;
NumOfProduct++;
return true;
}
My question is: when I make the object and add it to the array it gives me NullPointerException - why that happened?
As far as I understood, the line which cause NPE is
x.addProduct(s);
Most likely this is caused by array arrProduct which is not initialized and cause NPE when it is being accessed.
To fix that, please verify that arrProduct is always correctly initialized at Store object creation.

java: try finally blocks execution [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Strange finally behaviour? [duplicate]
(7 answers)
Closed 9 years ago.
I am confused about the try-finally execution when there exists return; in the try block. In my understanding, the finally block will always be executed, i.e. before returning to the calling method. While considering the following simple code:
public class TryCatchTest {
public static void main(String[] args){
System.out.println(test());
}
static int test(){
int x = 1;
try{
return x;
}
finally{
x = x + 1;
}
}
}
The result printed is actually 1. Does this mean the finally block is not executed? Can anyone help me with it?
When you return from try block, the return value is stored on the stack frame for that method. After that the finally block is executed.
Changing the value in the finally block will not change the value already on the stack. However if you return again from the finally block, the return value on the stack will be overwritten, and the new x will be returned.
If you print the value of x in finally block, you will get to know that it is executed, and the value of x will get printed.
static int test(){
int x = 1;
try{
return x;
}
finally{
x = x + 1;
System.out.println(x); // Prints new value of x
}
}
Note: In case of a reference value being returned, the value of reference is stored on the stack. In that case, you can change the value of object, using that reference.
StringBuilder builder = new StringBuilder("");
try {
builder.append("Rohit ");
return builder;
} finally {
// Here you are changing the object pointed to by the reference
builder.append("Jain"); // Return value will be `Rohit Jain`
// However this will not nullify the return value.
// The value returned will still be `Rohit Jain`
builder = null;
}
Suggested Read:
JVM Specs - Frames
The finally block is executed. The local variable is incremented. But the value of that local variable has already been copied for the return value.
From the Java Language Specification, 14.17: The return statement:
A return statement with an Expression attempts to transfer control to the invoker
of the method that contains it; the value of the Expression becomes the value of
the method invocation.
...
The preceding descriptions say "attempts to transfer control" rather than just "transfers
control" because if there are any try statements (ยง14.20) within the method or constructor
whose try blocks or catch clauses contain the return statement, then any finally
clauses of those try statements will be executed, in order, innermost to outermost, before
control is transferred to the invoker of the method or constructor. Abrupt completion of a
finally clause can disrupt the transfer of control initiated by a return statement
You are returning x before you exit try. I would do this:
public class TryCatchTest {
public static void main(String[] args) {
System.out.println(test());
}
static int test() {
int x = 1;
try {
do something with x.
} finally {
do something that will happen even in case of error;
x = x + 1;
return x;
}
}
}

Categories