I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand is that I've seen so much code that silently consume exceptions after printStackTrace
like this:
public void process() {
try {
System.out.println("test");
} catch(Exception e) {
e.printStackTrace();
}
}
There is similar code like this one in almost every Java article & project I ran into. Based on my knowledge this is very bad. The exception should almost always be forwarded to the outer context like this:
public void process() {
try {
System.out.println("test");
} catch(Exception e) {
e.printStackTrace();
throw new AssertionError(e);
}
}
Most of the time the exception should end up being handled at the outermost loop which belongs to the underlying framework (Java Swing for example). Why does it look like the norm to code like this in the Java world? I'm puzzled.
Based on my background, I'd prefer to remove printStackTrace entirely. I would simply rethrow as an unhandled aka RuntimeException
(or, even better, AssertionError
), then catch and log it at the most appropriate place: the framework outermost loop.
public void process() {
try {
System.out.println("test");
} catch(Exception e) {
throw new AssertionError(e);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…