Re: When to throw exceptions and when to use System.err?
Eric wrote:
Interesting you can crash that simple program by passing in null
instead of a String and Eclipse doesn't mention it.
That's not Eclipse's fault. You failed to tell it to report null pointer
problems.
So should every such error be thrown or trapped? It would seem such
Neither. It should be prevented.
error should be tracked down in the object where this method is
called, and trapping them all would be a real nuisance.
public void foo( String sometxt )
{
if (sometxt == null) {
throw new RuntimeException("That's a null not a String!");
That achieves exactly nothing. NPE already is a RuntimeException. Instead of
throwing a stone through the window you're throwing a baseball. Either way
you have broken glass.
}
System.out.println( "Input length "+ sometxt.length()
+" value\n\""+ sometxt +'"');
}
Which of these makes more sense?
public void foo(String fileName) throws Exception
{
try {
File myFile = new File(fileName);
myFile.createNewFile();
}
catch (Exception e)
{
throw e;
}
}
public int foo(String fileName)
{
int returnValue = 0;
try {
File myFile = new File(fileName);
myFile.createNewFile();
}
catch (Exception e)
{
returnValue = 1;
}
return returnValue;
}
Aside from tossing out numbers, the alternative to throwing the errors
would seem to be tracking down every possible reason for the error and
passing out..more numbers, or message strings?
YES! You absolutely MUST track down EVERY possible reason for error and
prevent it. THAT'S PROGRAMMING!
Why would you ever do otherwise? Do you actually want to leave possibility
for error in your program? Really? Why?
Again, don't catch exceptions, prevent them. Do you recall that I posted
upthread:
<http://java.sun.com/docs/books/effective/toc.html>
Item 57: Use exceptions only for exceptional conditions
Item 58: Use checked exceptions for recoverable conditions and runtime
exceptions for programming errors
Item 60: Favor the use of standard exceptions
*Item 62: Document all exceptions thrown by each method*
*Item 65: Don't ignore exceptions*
Buy that book and study it.
public void foo( String sometxt )
{
System.out.println( "Input length "+
(sometxt == null? 0 : sometxt.length())
+" value\n\""+ sometxt +'"' );
}
--
Lew