View RSS Feed

My Java Tips

Error codes lookup

Rate this Entry
by , 11-06-2011 at 07:02 PM (1878 Views)
There are sometimes situations, when you need some look up mechanism. I will present few example in the next few posts.

Let me present an scenario. We have an application which reads and writes to files on a file system. We have defined a error generating and tracking mechanism as well. Each error is assigned an error code and that code is thrown in case an error is encountered. To Interpret the code, we need to have some lookup mechanism.

I defined a final class with the error code mapping in a HashMap.

Java Code:
public final class ErrorCodes {

	private  HashMap hashMap = new HashMap();

	public ErrorCodes() {

		hashMap.put("00", "No error.");
		hashMap.put("10", "File locked.");
		hashMap.put("20","File does not exist.");
		hashMap.put("30","Folder does not exist.");
		hashMap.put("40","File is Read Only.");
		hashMap.put("30","File read error");
		hashMap.put("50","Unknown error");


	public  HashMap getHashMap() {
		return hashMap;
Now we need to lookup through the HashMap to get the error details.

ErrorCodes codes = new ErrorCodes();
FileApplication fileApp = new FileApplication();
int code =,"filename.txt");
System.out.println("Code retrieved: " + codes.getHashMap().get(code));

Its a simple of of retrieving code details from the map.

Here I will introduce another approach which uses static constants to define the meaning of error codes.

I have a class which defines the error codes using String constants.

Java Code:
public final class ErrorCodes {

public static final String _00 = "No error";
public static final String _10 = "File locked.";
public static final String _20 = "File does not exist.";
public static final String _30 = "Folder does not exist.");
public static final String _40 = "File is Read Only.");
public static final String _50 = "Unknown error");


public static String getValue (String fieldName) throws NoSuchFieldException, IllegalAccessException
Field field;
        	Class cl = SmppResponseCodes.class;
        	field = cl.getField(fieldName);
        	return field.get(cl).toString();

It looks easy, but the problem is how to lookup these since the codes will be thrown by the methods at run time. The getValue(...) method uses Reflection to get the error description. Let me show how to use this:

Java Code:
FileApplication fileApp = new FileApplication();
int code =,"filename.txt");
System.out.println("Code retrieved: " + ErrorCodes.getValue(code));
} catch (NoSuchFieldException e) {
catch (IllegalAccessException e) {
Hope this helps.

Submit "Error codes lookup" to Facebook Submit "Error codes lookup" to Digg Submit "Error codes lookup" to Submit "Error codes lookup" to StumbleUpon Submit "Error codes lookup" to Google

Tags: None Add / Edit Tags
Java SE