Unable to understand behaviour of Finally Block - java

I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.
class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod() throws Exception
{
throw new Exception(); /* Line 22 */
}
}

You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.
If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.

There is nothing to cause the program to exit.
The whole point of a catch block is to catch the exception and prevent it from propagating further.
After catching an exception, execution continues.

The finally block doesn't finalize the program, it just ensure to execute every time the try catch block runs whereas there is an exception or not..

It would print BC if you re-throw the exception in catch block.
catch (Exception ex)
{
System.out.print("B");
throw ex;
}
Then you'll have to declare your main as
public static void main(String [] args) throws Exception

Finally is called at the end of a try/catch block. It gets called even if the try fails and the catch is executed. The Finallyblock itself is only not executed if the program is killed somehow (JVM dies, forced to close, etc.)
In your example D is executing because it is outside of the try/catch/finally{} blocks.
There is a nice blog post on catching exceptions and the try/catch/finally behaviour here.

Which is correct. The above code will.
Try to execute badMethod and will fail
Execute the code in catch
Execute the code in finally
Continue in execution - print out the D

The finally block is processed after the try or catch block runs (depending on whether an exception was thrown/caught or not). If the exceptions were all caught properly and handles by the catch, it will run finally and then continue running the rest of the method.

Finally is the must executable block of java program.
It allows all the allocated resources of the currently running program to get free and make it available for the other applications if required.
This is mainly used when we share the common resources like Database or the devices.

Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.
And so in your case, badMethod throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.
In other words, if badMethod decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.
Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.
try
{
fooA();
}
finally
{
fooB();
}

Your program is functioning in the following way:
1. Call a bad method that throws an exception
2. Catch the exception
3. Execute the finally block
4. Resume
In Java, when an exception gets thrown it does not necessarily end program execution if the exception is handled. Your program does not actually handle the exception but catches it anyway and this is enough for the JVM to think it's ok to resume execution.
The output BCD is quite the right output.

Related

Sequential throw declarations in my Java code

'Hi, everyone! I have a question about exception handling in Java. What is launched firstly if there is sequential "throw" declarations and why? Below is an example of a method like that:
public void myMethod(boolean ok) {
if (ok) {
// do something...
} else {
throw new myRuntimeException();
throw new RuntimeException ();
}
}
Thanks in advance!
Most compiler would flag the second "throw" as error : "Unreachable code" - as it will never get executed.
It would be like writing code after a return (except a finally block) - it is never going to get executed - hence illegal.
Once you throw, the flow of execution is interrupted and the following happens:
if you are inside a try block, it goes to to the corresponding catch
if not, the Throwable (Exception in your case) is passed up the call chain, leaving myMethod() and going to the method that called it
this process is repeated until you either reach a try block or the top of the call stack, in which case your program will terminate.
Thus, only your first exception is thrown, the throw new RuntimeException (); statement is never reached.

How to go to catch block without throwing exception

I have a java class which is throwing IOException.I have some code in Catch block which i need to debug. I don't know in which case my java class is throwing exception. So I need to go to catch block explicitly without throwing. Can it be possible.
Please help me out.
Code in a catch block is not executed if no matching exception is thrown in the try block.
The only way to execute it is to cause the IOException to be thrown.
You can just put an explicit throw new IOException(); as the last line in the try block.
Alternatively, you might be able to pull the contents of the catch block into a separate method, which you can then invoke explicitly.
Control wont goto catch block if exception is not thrown. Put the code in finally block which you want to execute irrespective of whether exception thrown or not.
Sample:
try {
} catch() {
} finally {
//Put code here
}
but if the exception is thrown you will be directed towards finally block or you can post sample code so one might help you

What is the gist of finally block in Java?

I think on the following examples; but could not figure out what the importance of the finally block is. Can you tell me the difference of the executions of these two code samples? Also a real life example can be helpful.
Sample 1:
try{
// some code 1
}catch(Exception ex){
// print exception
}finally{
// some code 2
}
Sample 2:
try{
// some code 1
}catch(Exception ex){
// print exception
}
// some code 2
There is a big difference in the two snippets you've presented, e.g. when the catch block itself throws an exception, the finally block would still be executed by its semantics.
That is the following snippet prints "Finally!", but not "What about me???":
try {
throw null; // throws NullPointerException!
} catch (Exception e) {
int oops = 1/0; // throws ArithmeticException!
} finally {
System.out.println("Finally!"); // still gets executed!
}
System.out.println("What about me???"); // doesn't get executed!
Generally speaking, the finally of a try block practically always gets executed. There's no such guarantee for any code following the try block.
But what if my catch block is just a simple print statement?
There's still no guarantee that it won't throw something. Something could still go wrong in e.g. the construction for the exception detailed message.
Even if you make a best effort guarantee that the catch code is "safe" and the code following the try statement will always be executed, the question then becomes "Why?". Why avoid finally but then try so hard to replicate its semantics?
finally semantics is guaranteed, requiring no burden of proof from either the writer or the reader of the code. Precisely because of this, it's idiomatic to use finally block to put mandatory "clean-up" code. Using finally guarantees correctness and enhance both writability and readability.
The finally block is executed even if e.g. an Error is thrown, which is not caught by the catch block in your example. So you can put cleanup code in the finally block, which should be run always, regardless of the outcome of the operations in the try and catch blocks.
Note that usually catch blocks catch more specific types of exceptions - often only checked exceptions -, so in most cases the difference between the two code examples above is very definite.
Update: you may say that your catch block can never throw an exception, so finally is not needed. However, note two things:
this is only the current state of the code, and it can change in the future - can you guarantee that the future programmer who adds some potentially exception-throwing code in the catch block, will remember to put the cleanup code after it into a finally block?
try-catch-finally is a programming idiom which makes it easier for people reading the code to understand what's going on. If you don't use the common idiom, you risk misunderstanding, thus bugs on the long term.
You use the finally block in order to cleanup and run any code that should run whether an exception was thrown (and caught) or not. This includes code that you have in the catch block.
it is helpful when we want to free up the resources we used in try block. So the only place to execute them without missing at any case is finally block. Since if exception is thrown, java does not execute code which immediate after that. it directly jump to the catch block.
Note that you can have even try-finally without a catch:
try{
// some code
}finally{
// cleanup code
}
An example therefore could be a method that wants to propagate exceptions to the caller, but still needs clean up code, like releasing a look.
In case where the statements in try block throw unchecked exceptions, finally block will get executed allowing programmer to take relevant actions.
In real life, the finally block is used to close opened resources even if an exception occurs.
For example, when you read (or write) a file, when you access to a database, etc.
public void readFile(String fileName) {
FileReader fr;
BufferedFileReader bfr;
try {
fr = new FileReader(fileName);
bfr = new BufferedFileReader(fr);
// ...
} catch (IOException ioe) {
// ...
} finally {
// TO ENSURE THAT THE READERS ARE CLOSED IN ALL CASES
if (bfr != null) {
try {
bfr.close();
} catch (IOException ignoredIOE) {}
}
if (fr != null) {
try {
fr.close();
} catch (IOException ignoredIOE) {}
}
}
}

What does try do in java?

What does try do in java?
try is used for exception handling.
http://java.sun.com/docs/books/tutorial/essential/exceptions/try.html
The try/catch/finally construct allows you to specify code that will run in case an exception has occured inside of the try block (catch), and/or code that will run after the try block, even if an exception has occured (finally).
try{
// some code that could throw MyException;
}
catch (MyException e){
// this will be called when MyException has occured
}
catch (Exception e){
// this will be called if another exception has occured
// NOT for MyException, because that is already handled above
}
finally{
// this will always be called,
// if there has been an exception or not
// if there was an exception, it is called after the catch block
}
Finally blocks are important to release resources such as database connections or file handles no matter what. Without them, you would not have a reliable way to execute clean-up code in the presence of exceptions (or return, break, continue and so on out of the try block).
It allows you to attempt an operation, and in the event an Exception is thrown, you can handle it gracefully rather than it bubbling up and being exposed to the user in an ugly, and often unrecoverable, error:
try
{
int result = 10 / 0;
}
catch(ArithmeticException ae)
{
System.out.println("You can not divide by zero");
}
// operation continues here without crashing
try is often used alongside catch for code that could go wrong at runtime, an event know as throwing an exception. It is used to instruct the machine to try to run the code, and catch any exceptions that occur.
So, for example, if you were to request to open a file that didn't exist the language warns you that something has gone wrong (namely that it was passed some erroneous input), and allows you to account for it happening by enclosing it in a try..catch block.
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
}
An optional finally clause can be used after a try..catch block to ensure certain clean-up (like closing a file) always takes place:
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
} finally {
// Close the file object, so as to free system resourses.
file.close();
}
Exception handling
You're talking about a "try/catch" block. It's used to capture exceptions that may occur within the block of code inside the "try/catch". Exceptions will be handled in the "catch" statement.
It allows you to define an exception handler for a block of code. This code will be executed and if any "exception" (null pointer reference, I/O error, etc) occurs, the appropriate handler will be called, if one is defined.
For more information, see Exception Handling on wikipedia.

Calling a Java main function

I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?
Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.
It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?
With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.
Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.

Categories