Showing posts with label catch. Show all posts
Showing posts with label catch. Show all posts

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

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

Catch block

catch block handles the exceptions that are thrown inside the try block. Each try block has more than one catch blocks associated with it.

Syntax
    try {

   
    catch (ExceptionType name) {

    }
     catch (ExceptionType name) {

    }

Each catch block handles the type of exception indicated by its argument.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   System.out.println("inside Arithmetic Exception " + e);
  }
  catch(Exception e){
   System.out.println("inside Exception " + e);
  }
 }
}
   

Output
inside Arithmetic Exception java.lang.ArithmeticException: / by zero

Both handlers print an error message, but the program throwing ArithmeticException, so the code in the first handler executed and other not.

Some points to remember
1. While handling the exceptions, always handles the subclass exceptions first, next the super class.I.e, handle the ArithmeticException first, next Exception. Since ArithmeticExceptin is a subclass of Exception class. Other wise compiler throws error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(Exception e){
   System.out.println("inside IOException " + e);
  }
  catch(ArithmeticException e){
   System.out.println("inside Airthmetic Exception " + e);
  }
 }
}
       
When you tries to compile the above program, compiler throws the below error
 
ExceptionEx.java:11: error: exception ArithmeticException has already been caught
    catch(ArithmeticException e){
    ^
    1 error

2. A catch can contain try inside.
Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(Exception e){
   try{
   }
   catch(Exception e1){
   }
  }
 }
}
  



try                                                 Catching multiple 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