简体   繁体   中英

Custom Java exception printing when thrown

I want to design it such that whenever one of my custom exceptions is thrown, it automatically prints the stacktrace to a file. Is there a method I can override to accomplish this? Doing this would help to reduce a noticable amount of code in my project.

The stacktrace is available as soon as you call the constructor of your exception. You can't react to the event of being thrown, but you can write the stacktrace inside your constructor. If you have a common exception class that's the base of all your custom exceptions then you could do all this in its constructor.

您可以让您的自定义异常继承自RuntimeException,然后在相关的Threads上设置UncaughtExceptionHandler来查找您的异常并根据需要进行处理。

Is there a method I can override to accomplish this?

Yes, the printStacktrace() method.

You can create a base class for your exceptions and them call to an "internal" print that would be redeirected to your file.

You can use a Logger and have that specific logger pointing to the file you desire ( and change it, disable it , re-enable it, etc when you need to )

Something along the lines:

class MyStackTrace extends Throwable {
     public void printStacktrace() {
         super.printStracTrace();
         internalPrint();
     }
     private void internalPrint() {
         StringWriter sw = new StringWriter();
         printStackTrace( sw );
         Logger logger = Logger.getLogger("exceptions");
         logger.warning( sw.toString() );
     }
 }

I can'r help you print a stack trace when an exception is thrown. But it's easy enough to do when the exception is constructed - Just include the printStackTrace() in your custom exception's constructor.

In general, this is not a great idea to log on every exception creation. The catcher should really decide what is the best handling of an exception. Also overriding the method in exception and logging to a file breaks the general contract around exception.

On a side note, you may discover some horrible performance problem related to logging at later stage. Given overriding happens in a central place you will have hard time fixing this.

If you still want to log while throwing the exception then the better solution is to use/create a utility class like Throwables. Call the code as Throwables.logAndThrow(new CustomerException(...)), same one line of code but flexible for the long term. logAndThrow could be as simple as, using the logger technique of previous poster:

public static void logAndThrow(Throwable t) { logger.warning(t); throw t; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM