Showing posts with label finally. Show all posts
Showing posts with label finally. Show all posts

Sunday, 13 June 2021

Php: 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. Finally block mainly used to perform clean-up operation like closing file streams, flushing the data etc.,

 

A try block must associate with at least one catch or finally block.

 

Example

try{
    div(10,0);
}catch(LogicException $e){
    echo "Exception occurred: ". $e->getMessage();
}finally{
    echo "\ni will execute always";
}

 

Find the below working application.

 

finally_block_demo.php

 

#!/usr/bin/php

<?php 

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

   try{
    div(10,0);
   }catch(LogicException $e){
       echo "Exception occurred: ". $e->getMessage();
   }finally{
    echo "\ni will execute always";
   }
?>

 

Output

$./finally_block_demo.php 

Exception occurred: Division by zero
i will execute always

 

  

Previous                                                    Next                                                    Home

Sunday, 9 December 2018

JavaScript: What is the behavior, if finally block returns a value

HelloWorld.js
function get_value(){
  try{
    return 10;
  }catch(e){
    return 20;
  }finally{
    return 30;
  }
}

console.log(get_value());

What is the output of above program?
If a finally block returns a value, then the value returned by finally block is the return value for entire try-catch-finally block.

In the above example, 30 is printed to console.

Previous                                                 Next                                                 Home

Monday, 24 February 2014

Suppressed Exceptions

Exceptions thrown by the try clause suppressed by the exception raised in the finally block.

Example
import java.io.*;

class MyResource{

 void getResource(){
  throw new RuntimeException("I am the RuntimeException");
 }

 public void close(){
  throw new NullPointerException("I am the NullPointer Exception");
 }
}

Class MyResource has two methods, getResource(), which throws RuntimeException , and close(), which throws NullPointerException.

import java.io.*;

class SuppressEx{

 static void callResource()throws Exception{

  MyResource obj = new MyResource();

  try{
   obj.getResource();
  }
  finally{

  }
 }

 public static void main(String args[])throws Exception{
  callResource();
 }
}


Output
Exception in thread "main" java.lang.RuntimeException: I am the RuntimeException
      at MyResource.getResource(MyResource.java:6)
      at SuppressEx.callResource(SuppressEx.java:8)
      at SuppressEx.main(SuppressEx.java:15)

When you tries to run the above program, “ RuntimeException” is thrown. It is as expected. Now will put the close method in the finally block and see the result.
  
import java.io.*;

class SuppressEx{

 static void callResource()throws Exception{

  MyResource obj = new MyResource();

  try{
   obj.getResource();
  }
  finally{
   obj.close();
  }
 }

 public static void main(String args[])throws Exception{
  callResource();
 }
}

Output
Exception in thread "main" java.lang.NullPointerException: I am the NullPointer Exception
   at MyResource.close(MyResource.java:10)
   at SuppressEx.callResource(SuppressEx.java:11)
   at SuppressEx.main(SuppressEx.java:15)

As you observe the output, the exception thrown in the finally clause suppressed the exception thrown in the try clause.




Autocloseable interface                                                 java7 support for suppressed exceptions                                                 Home

try with Resources Statement

A resource is any thing that the program use in execution and must be closed once the program finished with it. Example, A FileInputStream object, FileOutputStream object etc.,

The try-with-resources statement ensures that each resource is closed at the end of the statement.

Syntax
try( resource1;
         resource2;
         …...
         resurce N ) {
}

Create input.txt file in the same folder, where your program resides

Example
import java.io.*;

class TryEx{
 public static void main(String args[]){
  try(
   FileInputStream fin = new FileInputStream("input.txt");
   FileOutputStream fout = new FileOutputStream("input.txt");
  ){
   for(int i = 97; i < 110; i++)
    fout.write(i);
   int b;
   
   while( (b = fin.read()) != -1){
    System.out.print((char)b +" ");
   }
  }
  catch(Exception e){
  }
 }
}
  
Output
a b c d e f g h i j k l m

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

In the above program, FileInputStream, FileOutputStream are used inside the try with resource statement, which implements the AutoClosable interface, So these resources closed once the try finished execution either normally or abruptly.

Try-with-resource statement doesn't need to have a catch or finally block associated with. The resurces closes in the reverse order.

Example
import java.io.*;

class MyResource implements AutoCloseable{
 String name;

 MyResource(String name){
  this.name = name;
 }

 public void close(){
  System.out.println("Closing Resource " + name);
 }
}

import java.io.*;

class SuppressEx{
 public static void main(String args[])throws Exception{
  try(
   MyResource obj1 = new MyResource("Resource 1");
   MyResource obj2 = new MyResource("Resource 2");){
  }
 }
}
Output
Closing Resource Resource 2
Closing Resource Resource 1

As you see the program, Resource 1 is created first, and Resource 2 next. But while closing the resources closed in the reverse order. In java the resource is anything that implements the AutoCloseable interface. And observe that, abve program doesn't associate any catch or finally for the try with resource block.

Some points to remember
1. A try with resource statement can have catch, finally block associated with. But these are executed once the resources created by try with resource closed.

Example
import java.io.*;

class MyResource implements AutoCloseable{
 String name;

 MyResource(String name){
  this.name = name;
 }

 public void close(){
  System.out.println("Closing Resource " + name);
  throw new RuntimeException("I am RuntimeException for the resource " + name);
 }
}

import java.io.*;

class SuppressEx{
 public static void main(String args[])throws Exception{
  try(
   MyResource obj1 = new MyResource("Resource 1");
   MyResource obj2 = new MyResource("Resource 2");){
  }
  catch(Exception e){
   System.out.println("I am in catch block " + e);
  }
  finally{
   System.out.println("I am in finally block");
  }
 }
}
  
Output
Closing Resource Resource 2
Closing Resource Resource 1
I am in catch block java.lang.RuntimeException: I am RuntimeException for the resource Resource 2
I am in finally block

As you observe the output, An exception thrown while closing the resource 2, so the catch block associated with the try-with-resource statement executed and after that finally executed.

throw vs throws                                                 autocloseable interface                                                 Home

Saturday, 22 February 2014

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. Finally block mainly used to perform clean up operation like closing file streams, flushing the data etc.,

A try block must associate with at least one catch or finally block.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  finally{
   System.out.println("I am finally block");
  }
  System.out.println("I am not going to executed");
 }
}

Output
I am finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionEx.main(ExceptionEx.java:5)
 
Observe the output, before throwing the exception, the code in the finally is executed. One more thing is above program doesn't handle the exception, so after executing the finally block, Java run time throws the exception and terminates the program.

finally always executes even the exception handled by the catch block.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(Exception e){
   System.out.println(e);
  }
  finally{
   System.out.println("I am finally block");
  }
  System.out.println("I am done with execution");
 }
}
 
Output
java.lang.ArithmeticException: / by zero
I am finally block
I am done with execution

The runtime system always executes the statements within the finally block regardless of what happens within the try block.

class ExceptionEx{
 static int print(){
  try{
   return 10;
  }
  finally{
   System.out.println("I am finally block");
  }
 }

 public static void main(String args[]){
  int var = print();
  System.out.println("value of var is" + var);
 }
}


Output
I am finally block
value of var is10
  
Above program called the return statement, even then also finally executed.

Some Points To Remember
1. What is the Output of the below Program ?
class ExceptionEx{
 static int print(){
  try{
   return 10;
  }
  finally{
   return -1;
  }
 }

 public static void main(String args[]){
  int var = print();
  System.out.println("value of var is " + var);
 }
}

Output
value of var is -1

Since the finally block execute even prgram calls return from the try block. So the value returned by try block is 100 overridden by the value -1.

2. What is the output of the below Program ?
class ExceptionEx{
 static int print(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   System.out.println(e);
   return 100;
  }
  finally{
   return -1;
  }
 }

 public static void main(String args[]){
  int var = print();
  System.out.println("value of var is " + var);
 }
}


Output
java.lang.ArithmeticException: / by zero
value of var is -1

3. What are the situation that finally can't execute ?
a. If the JVM exits while the try or catch code is being executed, then the finally block may not execute

b. if the thread executing the try or catch code is interrupted or killed, the finally block may not execute.

4. What is the output of the below program ?
class ExceptionEx{
 static void print(){
  try{
   System.out.println("I am in try");
   System.exit(0);
  }
  finally{
   System.out.println("I am in finally");
  }
 }

 public static void main(String args[]){
  print();
 }
}
 
Output
I am in try


Calling system.exit() terminates the program, so finally can't execute.

Multiple Exception                                                 throw exceptions                                                 Home

try block

Syntax
try {
   //code
}
catch and finally blocks . . .
The first step to handle the exception is enclose the error prone code in the try block. A try blcok must have at least one catch or finally block. Other wise compiler throws an error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(" I don't have any catch or finally blocks associated with me");
  }
 }
}
   
Above program, doesn't have any catch or finally block associated with it. So when you tries to compile the program, compiler throws the below error.

ExceptionEx.java:4: error: 'try' without 'catch', 'finally' or resource declarations
try{
^
1 error

try nested inside a try
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println("I am enclosing another try inside me");
   try{
    System.out.println(10/0);
   }
   catch(ArrayIndexOutOfBoundsException e){
    System.out.println("inside catch block " + e);
   }
  }

  catch(Exception e){
   System.out.println("Outside catch block " + e);
  }
 }
}
 
Output
I am enclosing another try inside me
Outside catch block java.lang.ArithmeticException: / by zero

As you observe the program, try has try nested in it. “10/0” is called in inside try block, which has catch block associated with it. But the catch block for the inner try block handles ArrayIndexOutOfBoundsException only. So while executing, the catch correspond to the outer block is executed.


Handling Exceptions                                                 catch block                                                 Home

Handling the Exceptions

Java platform provides 3 blocks blocks to handle the exception that may occur in the program.

Those are :
1. try block
2. catch block
3. finally block

Whenever you felt that, there is a possibility of occurring an exception in the code, then place the entire code in the try block. Provide handlers to handle the exception.

After a method throws an exception, the run time system tries to find exception handlers to handle it.

If the Run time system finds a handler to handle the exception, then it executes the block of code in the handler, and Proceed execution from the catch block onwards. Other wise program simply terminates.

Example
class ExceptionEx{
 void print(){
  System.out.println(10/0);
 }

 void callPrint(){
  print();
 }

 public static void main(String args[]){
  ExceptionEx obj = new ExceptionEx();

  try{
   obj.callPrint();
  }

  catch(ArithmeticException e){
   System.out.println("Seems to be an Arithmetic Exception Occurred");
  }
  System.out.println("Finished Execution");
 }
}
 
Output
Seems to be Arithmetic Exception Occurred
Finished Execution

As you observe the output, there is an AirthmeticException occurred, then Java run time system attempts to find out a handler to handle this exception, So it executed the statements inside the catch block. Once the statements in the catch executed, then the statements after the catch statement starts executing.

Exception                                                 try block                                                 Home