Despite reading many articles (some on this board) I am still scratching my head wondering when the appropriate time to use an exception would be. I don't see many methods returning error codes in the platform API, but some people still insist that exceptions should only be used for exceptional events that require control flow to jump specifically. I have been using exceptions to handle generic conditional assertions in my programs. Is this bad practice? Or should I use the old method of returning an error code for generic failures?
Asked
Active
Viewed 298 times
0
-
possible duplicate of [When to use exceptions in Java (example)](http://stackoverflow.com/questions/3213094/when-to-use-exceptions-in-java-example) – wsanville Nov 02 '11 at 01:03
1 Answers
4
I have been using exceptions to handle generic conditional assertions in my programs. Is this bad practice?
Yes, use validation instead.
Or should I use the old method of returning an error code for generic failures?
No, use an exception instead.
So, it should be ( just saying )
if( isValidIndex() ) { // <-- Validation : GOOD
return array.atPosition( x );
}
Instead of :
try {
doSomethingHazzarous();
} catch( ArrayIndexOutOfBoundsException aioobe ) {}
And it should be:
void somethingStreange() throws IllegalStateException {
somethingsWrongWithTheState();
}
Instead of:
void somethingStranger() {
int code = somethingsWrongWithTheState(); // <-- Error code: BAD
if ( code == SomeClass.ILLEGAL_STATE ) {
internalFlag = SomeOther.SOME_STATE;
return;
}
}

OscarRyz
- 196,001
- 113
- 385
- 569
-
Why then does the FileInputStream, for example, throw an IOException if the file requested does not exist rather than returning an error code to indicate the failure? Also, how can a failure condition be identified from within a constructor if it cannot return a value? – oldSkool Nov 02 '11 at 02:19
-
Because files may be deleted by an external program. You should code `File f = new File("someFile"); if ( f.exists() ) { new FileInputStream( f ) ; etc. ) ` that is validate it's existence and then do something with that file. If the file is deleted by other process then the exception will be thrown. – OscarRyz Nov 02 '11 at 03:44
-
As for the second, you don't that's the point, you throw an exception if needed in the constructor. – OscarRyz Nov 02 '11 at 03:44