aspose file tools*
The moose likes Java in General and the fly likes Exceptions or error codes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exceptions or error codes" Watch "Exceptions or error codes" New topic
Author

Exceptions or error codes

Joe Smith
Greenhorn

Joined: Oct 31, 2007
Posts: 8
Hi all,
I'm wondering when we should use error codes as used in languages such as C and when to use exceptions. Consider the following example in which we need a getData() function which should return a string of data if successful and error messages otherwise. How should we report errors? as exceptions or error messages?

public int fo(arguments){
//some code
String data="";
String errMsg="";
boolean rc=getData(arguments, data, errMsg);
// do something based on the results of getData()
// and report error messages in case of errors

}

What do you thing about the following implementation:

boolean getData(some arguments, String data, String errorMessage){
{//check arguments for null pointers or invalid values and return error
//message
errorMessage = "Invalid Arguments";
return false;
}
{
//check for other errors
errorMessage = "Some Error";
return false;
}
// no error, return valid data
data="some valid data";
return true;
}

As far as I know we shouldn't use exceptions for flow control. Could you please comment on proper use of error codes and exceptions?

Thanks
Joe
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Easy question to answer.

When do you use error codes? Never. Java doesn't support them. Well, it might if you use System.exit(1), but most applications don't give you access to the 1 in the first place, so forget about error codes altogether.

When do you use Exceptions? All the time.

I can't see how your example getData method is supposed to work. You are reassigning a String as an output parameter (ouch!) but there is no way for your calling method to gain access to that parameter.
On this website you will find the CampFire Stories; look for those called CupSize and Pass-by-Value Please. Those show how references are passed, and in the second it shows how the reference to "A" is unchanged. So you cannot pass data back like that. There are some classes where you might get an output parameter to work, but not String. You would have to get your method to return an object of some sort which encapsulates the data.

If anything goes wrong, you need to throw an exception. Read the Java Tutorials and look for Exceptions. Do a search through the Ranch for posts about Exceptions.
How you handle exceptions? Well, you will probably want to come back because the number of different opinions you get about Exceptions is equal to the number of people you ask!

Good luck with it.
[ March 31, 2008: Message edited by: Campbell Ritchie ]
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

That's a beautiful explanation by Campbell.

Of course, thats a good question as well which ignites the thinking capability . Obviously those two are the eligible candidates to get back to the user indicating the status of the operation. Exceptions and Error codes. But it depends on the language or environment which hosts your applications.

In C and C++, you mostly deal with the error codes which are mostly of integer values. In general 1 means success and 0 means failure (certain times it may be of -1). But as campbell said, Java does take away all these points and it keeps "exceptions" in place.

You may ask whats the big deal? Yes, one way what i could think of is no matter what, you have keep checking on the return status. In case of exception, the complete flow of control is taken into the different part of your program and unnecessarily it was not allowed to proceed further after knowing that something unwanted happens.

So dealing with exceptions is beneficiary to programmers/developers.

Does that satisfy/convince?


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12779
    
    5
Remember, you can create your own custom Exception class that can hold and report all of the information you might need to uncover why the failure occurred. Thats one of the things I love about the Java exceptions mechanism. I hope I never see another numeric error code again.

Bill
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3527
    
  15
Originally posted by Campbell Ritchie:
When do you use error codes? Never. Java doesn't support them. Well, it might if you use System.exit(1)


This assumes the OP wants to return an error code from his program to the operating system. From his example, it looks more like he wants to return an error code from one Java method to another. If you are writing an API, that would be a quite legitimate way to indicate an error to the programmer whose code is using your API.
Take the HttpURLConnection class for example. After you call the connect method, you then need to call the getResponseCode method to find out the result. Okay, this isn't returning an error code directly from the connect method, but it is still making use of error codes to indicate the result of an operation instead of an exception..
[ March 31, 2008: Message edited by: Joanne Neal ]

Joanne
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
I see what you mean, Joanne. It's a bit like an indexOf() method which returns -1 when it finds nothing.
Joe Smith
Greenhorn

Joined: Oct 31, 2007
Posts: 8
Thanks all for your great comments! I know Exceptions and I have been using them since I've learned Java, but my question was whether we should always use them to report and checks errors in our code. By 'error' I mean errors in general which by Java definition are 'Exceptions' e.g. IllegalArguments or NullPointerArguments. Using 'Exceptions' is not without controversies though.

The example I gave was based on C mentality. Any way based on your comments I think the Java solution to the problem in my example without using too many ugly try/catch every time we use the API, is to use custom exceptions and define my own 'error message' when throwing exception. something like the following:

String getData(some arguments) throws MyException, Exception {
// error condition 1:
throw new MyException("Error Message_1");

// error condition 2:
throw new MyException("Error Message_2");

// error condition 3:
throw new MyException("Error Message_3");

// success:
String data=.....
return data;
}

In the calling method:

void foo(){

String data;
try {
data=getData(arguments);
} catch (Exception e){ // one catch for all the exceptions thrown from the getData() method
// handle exception
}
}

public class MyException extends Exception {
myException(String msg) {
super(msg);
}
}

I think this solution handles many potential exception/errors in a clean and efficient way. Any comments/suggestions about this?

Thanks

Joe
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Haven't read the whole of your code, but the custom exception with different messages looks a very good solution.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

That's correct. It will be useful in multi-layered applications (in web applications) where in you can pass the error code from the last layer where it can be looked at the properties file for fetching the appropriate message in the front end.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exceptions or error codes