I am very new to Java. I am writing a program to read a file, compute its SHA1 checksum, and write the result to another file. On any error I am calling a function err_exit() that prints a message to stderr and terminates execution by calling System.exit() with a specified exit status. This is approximately what my main() function looks like:
public static void main(String[] args) { String in_fname = "C:/tmp/test.txt"; // not reading args yet String out_fname = "C:/tmp/test.sign"; byte[] file_data; String hexdigest; try { file_data = readFileAsByteArray(in_fname); } catch (java.io.IOException ex) { file_data = new byte[] {0}; // note this line well, please err_exit(2, "error opening input file '" + in_fname + "'"); } try { hexdigest = hexdigestSha1(file_data); } catch (NoSuchAlgorithmException ex) { hexdigest = ""; // note this line well, please err_exit(3, "could not compute SHA1 message digest!"); } try { writeFileFromString(out_fname, hexdigest); } catch (java.io.IOException ex) { err_exit(2, "error writing output file '" + out_fname + "'"); } System.exit(0); // success } There are two lines that I asked you to note well. Both of those lines exist simply to keep the compiler from complaining that the variable might not be initialized.
As far as the compiler can tell, the catch block might continue. Actually err_exit() will never return so there is no chance of an invalid value being passed along.
So, my question: what is the usual Java idiom for handling this sort of thing? The row of try/catch blocks is sort of ugly; would you recommend I make the various functions call err_exit() and not have the code explicit like this? I think I prefer the explicit checks, and the main() function is the right place to do the checking, but I'm interested in feedback.
If I am going to have the try/catch blocks, is this a good way to silence the compiler warnings?
If I were doing this in Python, I'd likely just not catch the exceptions, and let the program stop with a stack trace. A stack trace on error won't shock the user of this program, since that user is me. It occurs to me that if I declared my main() function as throws Exception that I could then not catch the exceptions and it would behave something like Python. Is that a horrible idea that would make right-thinking Java people shun me?
P.S. If you have a favorite book/web page/whatever of Java idioms that I should read, please mention it.
EDIT: I apologize for the variable names with underscores. I have already renamed the ones in my real program, but I am going to leave them as-is here. It's actually because I have spent a lot of time programming in Python and C; I was either using Python "PEP 8" style or generic C style, take your pick.