Implementation of Finally Block - java

In the Code written below although i have not caught the ArithmeticException,yet the exception is handled automatically and with finally Block, the content of main() method is successfully Executed. Whereas if i remove the return statement from finally and make demo as returning void then the program after executing finally block throws MainThread Exception..why is it so?
public class FinallyDemo {
int demo() {
try {
int a=5/0;
}
finally {
System.out.println("Finally Executed");
return 10;
}
}
public static void main(String s[]) {
int a=new FinallyDemo().demo();
System.out.println("Exception Handled");
}
}

Because you return from the finally block, the exception is silently disposed. You should never return from a finally block! (Well, almost always never).
From the Java Language Specification:
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
This also means if you threw a different exception, like an IllegalStateException, from the finally block, the original exception would also be discarded.

Related

How finally block works?

hello community in my tutorial this week I found out that all threads stop when java gets a runtime error, but in the finally code block this event looks a bit strange.
public class main {
public static void main(String[] args) {
try {
Scanner kb = new Scanner(System.in);
System.out.println("enter number:");
double val = Double.parseDouble(kb.nextLine());
double result = MathUtil.myLog(val);
}
catch (MyException ex) {
System.out.println("Cath:foo");
}
finally {
System.out.println("foo:finally");
}
}
class MathUtil {
public static double myLog(double val)
{
if (val < 0)
throw new MyException();
if(val == 0)
throw new YourException();
return Math.log(val);
}
class MyException extends RuntimeException {
}
class YourException extends RuntimeException {
}
When i execute this code and make an incorrect entry it first executes the finally block and then I get runtimeError.
Works as indented, doesn't matter if catch clause catch an error, finally as it says will execute almost every time. It won't execute only if JVM runs out of memory but it's rare corner case
This works as designed :-) From the documantation from oracle:
'The finally block always executes when the try block exits..'
For me this means the finally block will be executed before the catch block or anything else is executed.

Regarding excuting finally block in system.exit case also by adding shutdownhook [duplicate]

This question already has answers here:
How does Java's System.exit() work with try/catch/finally blocks? [duplicate]
(6 answers)
Closed 9 years ago.
I have developed a program in which the case of return statement either inside try block or catch block the finally block executes at last but when I write system.exit inside try block in this case the finally block not executed but still I want to execute , could you please advise do I need to add Runtime.getRuntime().addShutdownHook in that case I need to add the code that should be executed in any case , even if system.exit is called. please advise , below is my class
public class Hello {
public static void hello(){
try{
System.out.println("hi");
System.exit(1);
// return;
}catch(RuntimeException e)
{ //return;
}
finally{
System.out.println("finally is still executed at last");
}
}
public static void main(String[] args){
Hello.hello();
}
}
1) in general you do need a shutdown hook if you want to execute some code after exit
public static void main(String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("bye");
}
});
hello();
}
2) in this concrete case there's no need for shutdown hook, just remove exit from the code
public static void hello() {
try{
System.out.println("hi");
} catch (RuntimeException e) {
//
} finally{
System.out.println("finally is still executed at last");
}
}
when you are calling System.exit(1)
it exits your program and JVM stops the execution of your program by force .
so why would you use System.exit(1) if you want some code to execute after the exit
simply apply some condition within yout try block to exit try block , which leads to finnaly block in every case

Trouble with a thread-safe queue class. Specifically, with exceptions

I am using a thread-safe queue class and have a problem with the insert method I've defined. A Buffer stores an array (elementData) that uses the start/end variables to know where to add/delete stuff from the queue. It's thread-safe, so it uses synchronized methods so I can have multiple threads refer to the same buffer.
public class Buffer<T> {
private T[] elementData;
private int elementCount;
private int start;
private int end;
// Additional fields
// Code to instantiate a Buffer, other methods (e.g. delete)
public synchronized void insert(T t) throws InterruptedException {
while (elementCount == elementData.length) {
wait();
}
end = (end + 1) % elementData.length;
elementData[end] = t;
elementCount++;
notifyAll();
}
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
b.insert(3);
}
}
Here's my understanding of the situation. When a method such as insert is called, we want to be able to throw an exception that could happen when the main method or some other thread gets called and tries to perform insert while it's suspended. But what I don't understand is why I get this unreported exception. I thought that having a "throws InterruptedException" after the method would be sufficient. Do I need a "try" block? My attempts with try blocks have all failed, so I'm a little stumped as to how to fix this error.
Also, I'm aware that I don't have any actual threads running. I'll do those once I can fix this unreported exception. :) Thanks to anyone who can help.
Buffer.java:56: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
b.insert(3);
The compile exception is because your insert method could throw an InterruptedException (even if you're not throwing it on purpose), so every method that calls it must use a try/catch block, even if the error never arises:
public static void main(String[] args) {
Buffer<Integer> b = new Buffer();
try {
b.insert(3);
} catch(InterruptedException ie) {
//error handling
e.printStackTrace();
}
}

return statement and exception in try block in java

public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
in this problem try block has return statement and throws exception also...
its output is COMPILER ERROR....
we know that finally block overrides the return or exception statement in try/catch block...
but this problem has both in try block...
why the output is error ?
Because your return statement is unreachable - the execution flow can never reach that line.
If the throw statement was in an if-clause, then the return would be potentially reachable and the error would be gone. But in this case it doesn't make sense to have return there.
Another important note - avoid returning from the finally clause. Eclipse compiler, for example, shows a warning about a return statement in the finally clause.
The compiler exception come from, like my Eclipse dude says
Unreachable code Test2.java line 11 Java Problem
The return statement of your main code block will never be reached, as an exception is thrown before.
Alos notice the return statement of your finally block is, at least, a design flaw, like Eclipse once again says
finally block does not complete normally Test2.javajava line 14 Java Problem
Indeed, as a finally block is only here to provide some clean closing, it is not expected to return something that would override the result normally returned by the method.
The throw new Exception() will be called no matter what, so anything within the try block that follows the throw is Unreachable Code. Hence the Error.
public class Test2 {
public static void main(String args[]) {
System.out.println(method());
}
public static int method() {
try {
throw new Exception();
return 1; //<<< This is unreachable
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
It should eventually return 3.
Because 'return' keyword within try block is unreachable, that's why you are getting compile-time error. Omit that 'return' keyword from try block, and then run your program, your will successfully compile.

Why does my code seem to bypass this exception?

Given this code:
public class TwoThreads {
static Thread laurel, hardy;
public static void main(String[] args) {
laurel = new Thread() {
public void run() {
System.out.println("A");
try {
hardy.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
hardy = new Thread() {
public void run() {
System.out.println("D");
try {
laurel.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
laurel.start();
hardy.start();
}
}
The output includes:
A C D E and F
I'm puzzled about why F is included, given that an IllegalMonitorStateException is thrown when wait() is called outside of synchronized code. Why is the print statement of F reached? I believe that the thread stack blows then, but then the program should pass control to its main stack.
Is this correct?
You are catching the exception in the block that prints "E" effectively swallowing it. The code will then continue on to print "F". Blocks that simply catch exceptions and do nothing else are dangerous for this reason.
you catch the exception so control goes to the catch block then continues executing the code after the try/catch.
In the code above as long as their are non application fatal errors after "D" is printed, "F" will always be printed as all catchable errors are handled.
If there are no thread hangs, this behaviour will be consistent.
Add a boolean check to "F" which is suppressed if there is an error thrown and that will give you the desired behaviour.
As a side note, you're calling Thread's static sleep method on objects, which does something other than you might expect. You shouldn't call static class methods on instances for this reason.
(As for why F is printed, the other guys are correct)
I wonder how you know IllegalMonitorStateException is being thrown. You are consuming any Exception and not doing something like e.printStackTrace();.

Categories