Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Closing log file, use of System.exit()

843810Sep 27 2004 — edited Sep 27 2004
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
        }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 25 2004
Added on Sep 27 2004
1 comment
336 views