Friday, 9 January 2015

Creating Custom Exception Classes in Java

Hi Guys,
In this post we are going to see how to create an Custom Exception classes in Java.

Java provides a lot of exception classes for us to use but sometimes we may need to create our own custom exception classes to notify the caller about specific type of exception with appropriate message and any custom fields we want to introduce for tracking, such as error codes. For example, let’s say we write a java code for processing files and formatting number, so we can provide caller with appropriate error code when when file is not found and when we try to format a String to number.
Here is an example of custom exception class and showing it’s usage.

CustomException.java
package in.customexep;

public interface CustomException {

void processErrorCodes(MyException e) throws MyException;

void processFormatNumber() throws MyException;

void processFiles(String file) throws MyException;

}


MyException .java
package in.customexep;

public class MyException extends Exception {

private static final long serialVersionUID = 1L;

private String errorMessage="Unknown Exception";
 
    public MyException(String message, String errorMessage){
        super(message);
        this.errorMessage=errorMessage;
    }
   
    public String getErrorCode(){
        return this.errorMessage;
    }

}

CustomExceptionImpl .java
package in.customexep;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class CustomExceptionImpl implements CustomException {

public static void main(String[] args) throws MyException {
CustomException customExep = new CustomExceptionImpl();
try {
//customExep.processFiles("file.txt");
customExep.processFormatNumber();
        } catch (MyException e) {
        customExep.processErrorCodes(e);
        }
   
}

@Override
public void processErrorCodes(MyException e) throws MyException {
// TODO Auto-generated method stub
if(e.getErrorCode().equals("Number_Format_Exception"))
{
System.out.println("Number Format Exception Occured");
throw e;
}
else if(e.getErrorCode().equals("FILE_NOT_FOUND_EXCEPTION"))
{
System.out.println("FILE_NOT_FOUND_EXCEPTION Occured");
throw e;
}
else if(e.getErrorCode().equals("FILE_CLOSE_EXCEPTION"))
{
System.out.println("FILE_CLOSE_EXCEPTION Occured");
throw e;
}
else
{
System.out.println("Unknown exception occured, lets log it for further                       debugging."+e.getMessage());
            e.printStackTrace();
}

}

@Override
public void processFormatNumber() throws MyException {
// TODO Auto-generated method stub
try
{
String a ="ten";
int formatNumber = Integer.parseInt(a);
System.out.println(formatNumber);
}catch(NumberFormatException e)
{
throw new MyException(e.getMessage(), "Number_Format_Exception");
}

}

@Override
public void processFiles(String file) throws MyException {
// TODO Auto-generated method stub
InputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");
        }finally{
            try {
                if(fis !=null)fis.close();
            } catch (IOException e) {
                throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION");
            }
        }

}

}

So, Now we run our program with processFormatNumber method. Here I am trying to convert the String to number format. Here i will get NumberFormatException because i am trying to convert String to number. Here is the Output.

That’s all for creating custom exception classes and handling in java, I hope you liked it and learned something from it.

Wednesday, 3 December 2014

ISO 8601 time stamp to Java time stamp using Joda-Time API

Hi Guys,

In this post we are going to see how to convert ISO time stamp to Java and oracle time stamp using Joda-Time API.

Joda-Time provides a quality replacement for the Java date and time classes.
Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).
For more details on Joda-Time API refer http://www.joda.org/joda-time/.
Let's see how to implement Joda-Time API for converting ISO to Java time stamp. We need to include joda-time-1.6.jar or latest version of dependency for working with Joda-Time API. 


package in.jodatime;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.*;

public class Jodatime{

public static void main(String[] args) throws ParseException {

DateTimeFormatter parser = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2014-11-06T18:18:47+0000"; // ISO Timestamp
DateTime dateTime = parser.parseDateTime(jtdate); // Parse ISO timestamp
String tempDate = dateTime .toString();
System.out.println(tempDate);

  //Create SimpleDataFormat For converting from ISO to Java and to Oracle
SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd'T'h:mm:ss");
Date date = dateFormat .parse(tempDate );
System.out.println(date);

dateFormat = new SimpleDateFormat("dd-MMM-yy h:mm:ss a", Locale.ENGLISH);
String formatDate = dateFormat .format(date);
System.out.println(formatDate );

}
}


Output:

That's all Folk's..