Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I throw an exception or print out an error statement in a program?

Tags:

java

styles

I have my program working and all done (java). It's a short and easy program for a job interview. I handle stuff like improper input format by throwing a custom exception. Is that the best way to do it or should I just make a print statement?

like image 722
Smipims Avatar asked Sep 01 '13 03:09

Smipims


1 Answers

Exceptions are only useful if they will be handled by other code.

If you're writing a reusable library, you should by all means throw an exception.
There is nothing more frustrating than calling a third-party library that logs errors to the console instead of telling your code about them.

However, if you're writing a standalone utility, it's nicer to print friendly error messages than an ugly stack trace.

The most flexible approach is to write reusable code that throws exceptions, then add catch blocks in main() (or elsewhere in the standalone portion) that prints friendly messages.

like image 183
SLaks Avatar answered Nov 15 '22 03:11

SLaks