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.
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.
You can have your custom exceptions inherit from RuntimeException, then set the UncaughtExceptionHandler on the relevant Threads to look for your exceptions and handle them however you like.
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() );
}
}
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; }