The goal is:
- to log user messages as well as the exception; and
- return non-zero exit code in the case of exception.
I'm stack at a peace of code that may be summarized as following:
class LoggerFile {
final FileWriter f;
LoggerFile(String fName) throws Exception {
f = new FileWriter(fName);
}
public void log(String msg) throws IOException { f.write(msg);}
public void close() throws IOException { f.close(); }
}
class LogTrouble {
// plz note that the main throwing exception returns exit code 1
public static void main1(final String[] args) throws Exception {
final LoggerPs logger = new LoggerPs("1.log");
try {
logger.log("ok");
logger.log(1/0 + "bad"); // throws an exception
logger.log("done");
} finally {
System.out.println("I do not know about the exception");
logger.close();
}
}
The finally-clause would be a great place to log the exception but we should catch it before. This neglects the use of finalizer in this case. Furthermore, it does not catch Throwables and Errors. In addition, as the exception is catched the program will return exit code 0.
public static void main(final String[] args) throws Exception {
final LoggerPs logger = new LoggerPs("1.log");
try {
logger.log("ok");
logger.log(1/0 + "bad");
logger.log("done");
} catch (Exception e) {
logger.log("ERROR!" + e);
}
logger.close();
}
What is a design pattern to the issue? I've seen that use of System.exit() method it not appreciated as it abruptly terminates JVM. However, in my console application it seems feasible.
I have tried the following code but finally-clause is not executed in this case:
try {
try {
// throw error
} catch(Exception e) {
logger.log("ERROR!" + e);
System.exit(1);
}
} finally {
logger.close(); //never called
}