Showing posts with label java7. Show all posts
Showing posts with label java7. Show all posts

Monday, 24 February 2014

Java7 Support for Suppressed Exceptions

Throwable class provides one constructor and 2 methods to handle suppressed exceptions.

Constructor
protected Throwable( String message,
                                             Throwable cause,
                                 boolean enableSuppression,
                                 boolean writableStackTrace)

Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled. If suppression is disabled, getSuppressed() for this object will return a zero-length array and calls to addSuppressed(java.lang.Throwable)

Will discuss about the two methods which are used to find out the suppressed Exception details.

public final void addSuppressed(Throwable exception)
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception. Since this method is final, so it can't be overridden. The suppression behavior is enabled by default. If you want to disable the suppression behavior, make the flag enableSuppression to false in the above constructor.

public final Throwable[] getSuppressed()
Returns an array containing all of the exceptions that were suppressed.

import java.io.*;

class MyResource{
 String name;

 void exception1(){
  throw new RuntimeException("I am exception 1");
 } 

 void exception2(){
  throw new RuntimeException("I am exception 2");
 } 

 void exception3(){
  throw new RuntimeException("I am exception 3");
 } 

 void exception4(){
  throw new RuntimeException("I am exception 4");
 }
}
  

import java.io.*;

class SuppressEx{

 static Throwable suppressed = new Throwable();

 static MyResource obj1 = new MyResource();

 static void throwFirst(){
  try{
   obj1.exception1();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   throwSecond();
  }
 }

 static void throwSecond(){
  try{
   obj1.exception2();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   throwThird();
  }
 }

 static void throwThird(){

  try{
   obj1.exception3();
  }
  catch(Exception e){
   suppressed.addSuppressed(e);
   obj1.exception4();
  }
 }

 public static void main(String args[])throws Exception{
  try{
   throwFirst();
  }
  catch(Exception e){
   System.out.println(e);
  }

  System.out.println("--------------------------");
  System.out.println("Suppressed Exceptions are");
  System.out.println("--------------------------");

  Throwable[] suppressedExceptions = suppressed.getSuppressed();

  for(int i=0; i < suppressedExceptions.length; i++){
   System.out.println(suppressedExceptions[i]);
  }
 }
}

Output
java.lang.RuntimeException: I am exception 4
--------------------------------
Suppressed Exceptions are
--------------------------------
java.lang.RuntimeException: I am exception 1
java.lang.RuntimeException: I am exception 2
java.lang.RuntimeException: I am exception 3



Suppressed Exceptions                                                 Exception Hierarchy                                                 Home

AutoCloseable interface

AutoClosable interface esures that a resource is closed when it is no longer required. AutoClosable interface has one method in it. AutoClosable interface exist from java 1.7 onwards.

void close() throws Exception
closes the resource, when it is no longer required. This method executes automatically, for the resources maintained by try with resource statement. This method throws an exception if this resource cannot be closed

Some of the classes implementing the AutClosable interface are
FileInputStream, FileLock, FileOutputStream, FileReader, FileSystem, FileWriter, FilterInputStream, FilterOutputStream etc.,


try with resource statement                                                 Suppressed Exceptions                                                 Home

Saturday, 22 February 2014

Catching More Than One Exception with One Handler

Prior to Java7 one catch block able to handle one type of Exception. In java 7, a single catch block can handle more than one type of exception.

Syntax
    catch(ExceptionType1 | ExceptionType2 e ){

    }

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }

  catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
   System.out.println(e);
  }
 }
}
 
Output
java.lang.ArithmeticException: / by zero

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter “e” is final.

Some points to Remember
1. Trying to handle same type(subclass and super class like) of Exceptions in the catch block throws compiler error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }

  catch(ArithmeticException | Exception e){
   System.out.println(e);
  }
 }
}
  
Since ArithmeticException is a sub class of Exception class, so when you tries to compile the above program, compiler throws the below error.

ExceptionEx.java:7: error: Alternatives in a multi-catch statement cannot be related by subclassing
catch(ArithmeticException | Exception e){
^
Alternative ArithmeticException is a subclass of alternative Exception
1 error

catch block                                                 finally block                                                 Home

Wednesday, 5 February 2014

Control flow statements : Decision Making: switch

The body of a switch statement is known as a switch block. A statement in the switch block can be labelled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

switch works with the byte, short, char, and int primitive data types. It supports enums also

java 7 supporting strings also in switch case evaluation, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.

Integer, Char, Byte, Short are called wrapper classes. Will discuss about these more on coming posts.

Example
class SwitchEx{
 public static void main(String args[]){
  int day = 5;
  
  switch(day){
   case 1:
    System.out.println("Sunday");
    break;
   case 2:
    System.out.println("Monday");
    break;
   case 3:
    System.out.println("Tueday");
    break;
   case 4:
    System.out.println("Wednesday");
    break;
   case 5:
    System.out.println("ThursDay");
    break;
   case 6:
    System.out.println("Friday");
    break;
   case 7:
    System.out.println("Saturday");
    break;
   default:
    System.out.println("You entered wrong day number");
  }
 }
}

Output
ThursDay

Explanation
As you see in the above program, variable “day” set to the value 5. So in the switch case, case 5 is executed. If the day is set to 1, then case 1 will execute and come out of the switch.

You can see in the above program, each case has a break statement associates with it, is it necessary ? Yes of course, if you don't specify the break for case statements, then all the case statement below the evaluated case are executed.

And one more thing is, case statements need not be in proper order. They can be written in any way.

class SwitchEx{
 public static void main(String args[]){
  int day = 5;
  
  switch(day){
   case 2:
    System.out.println("Monday");
   case 3:
    System.out.println("Tueday");
   case 4:
    System.out.println("Wednesday");
   case 5:
    System.out.println("ThursDay");
   case 6:
    System.out.println("Friday");
   case 7:
    System.out.println("Saturday");
   case 1:
    System.out.println("Sunday");
   default:
    System.out.println("You entered wrong day number");
  }
 }
}

Output
ThursDay
Friday
Saturday
Sunday
You entered wrong day number


As you see in the above program, “day” is set to 5, and there is no breaks in the corresponding cases. So case 5, 6,7, 1 and default are executed.

One more thing is in the above program, case 1 came after 7, it is acceptable behaviour in java.

What is the necessity of default here
If no case is evaluated, then default executes, just like else block in if-else if-else ladder.

Example
class SwitchEx{
 public static void main(String args[]){
  int day = 9;
  
  switch(day){
   case 1:
    System.out.println("Sunday");
    break;
   case 2:
    System.out.println("Monday");
    break;
   case 3:
    System.out.println("Tueday");
    break;
   case 4:
    System.out.println("Wednesday");
    break;
   case 5:
    System.out.println("ThursDay");
    break;
   case 6:
    System.out.println("Friday");
    break;
   case 7:
    System.out.println("Saturday");
    break;
   default:
    System.out.println("You entered wrong day number");
  }
 }
}
 
Output
You entered wrong day number

Some points to remember
1. When to use if-else if -else ladder, than switch ?
Switch case won't supports range checks like age>30, year<2000 etc., in those cases better to go for if-else if-else ladder.
Control flow statements                                                 switch statement                                                 Home