<p>How can I detect when an Exception has been thrown anywhere in my application?</p>

<p>I'm try to auto-magically send myself an email whenever an exception is thrown anywhere in my Java Desktop Application.  I figure this way I can be more proactive.</p>

<p>I know I could just explicitly log and notify myself whenever an exception occurs, but I'd have to do it everywhere and I might(more likely will) miss a couple.</p>

<p>Any suggestions?</p>

[{'answer_id': 75274, 'author': 'toluju', 'author_id': 12457, 'author_profile': 'https://Stackoverflow.com/users/12457', 'pm_score': 0, 'selected': False, 'text': '<p>In this case I think your best bet might be to write a custom classloader to handle all classloading in your application, and whenever an exception class is requested you return a class that wraps the requested exception class. This wrapper calls through to the wrapped exception but also logs the exception event.</p>\n'}, {'answer_id': 75277, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 3, 'selected': False, 'text': '<p>The new debugging hooks in Java 1.5 let you do this.  It enables e.g. "break on any exception" in debuggers.</p>\n\n<p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/com/sun/jdi/event/ExceptionEvent.html" rel="noreferrer">Here\'s the specific Javadoc</a> you need.</p>\n'}, {'answer_id': 75285, 'author': 'Justin Rudd', 'author_id': 12968, 'author_profile': 'https://Stackoverflow.com/users/12968', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html" rel="nofollow noreferrer">Thread.UncaughtExceptionHandler</a>.  You can set it per thread or a default one for the entire VM.</p>\n\n<p>This would at least help you catch the ones you miss.</p>\n'}, {'answer_id': 75298, 'author': 'Mat Mannion', 'author_id': 6282, 'author_profile': 'https://Stackoverflow.com/users/6282', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re using a web framework such as <a href="http://www.springframework.org" rel="nofollow noreferrer">Spring</a> then you can delegate in your web.xml to a page and then use the controller to send the email. For example:</p>\n\n<p>In web.xml:</p>\n\n<pre><code>&lt;error-page&gt;\n  &lt;error-code&gt;500&lt;/error-code&gt;\n  &lt;location&gt;/error/500.htm&lt;/location&gt;\n&lt;/error-page&gt;\n</code></pre>\n\n<p>Then define /error/500.htm as a controller. You can access the exception from the parameter javax.servlet.error.exception:</p>\n\n<pre><code>Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");\n</code></pre>\n\n<p>If you\'re just running a regular Java program, then I would imagine you\'re stuck with public static void main(String[] args) { try { ... } catch (Exception e) {} }</p>\n'}, {'answer_id': 75302, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 0, 'selected': False, 'text': '<p>I assume you don\'t mean <em>any</em> Exception but rather any <em>uncaught</em> Exception.</p>\n\n<p>If this is the case <a href="http://java.sun.com/developer/JDCTechTips/2001/tt0109.html#handling" rel="nofollow noreferrer">this article on the Sun Website</a> has some ideas.  You need to wrap your top level method in a <code>try-catch</code> block and also do some extra work to handle other Threads.</p>\n'}, {'answer_id': 75439, 'author': 'shemnon', 'author_id': 8020, 'author_profile': 'https://Stackoverflow.com/users/8020', 'pm_score': 6, 'selected': True, 'text': '<p>You probobly don\'t want to mail on any exception.  There are lots of code in the JDK that actaully depend on exceptions to work normally.  What I presume you are more inerested in are uncaught exceptions.  If you are catching the exceptions you should handle notifications there.</p>\n\n<p>In a desktop app there are two places to worry about this, in the <a href="/questions/tagged/event-dispatch-thread" class="post-tag" title="show questions tagged &#39;event-dispatch-thread&#39;" rel="tag">event-dispatch-thread</a> (EDT) and outside of the EDT.  Globaly you can register a class implementing <code>java.util.Thread.UncaughtExceptionHandler</code> and register it via <code>java.util.Thread.setDefaultUncaughtExceptionHandler</code>.  This will get called if an exception winds down to the bottom of the stack and the thread hasn\'t had a handler set on the current thread instance on the thread or the ThreadGroup.</p>\n\n<p>The EDT has a different hook for handling exceptions.  A system property <code>\'sun.awt.exception.handler\'</code> needs to be registerd with the Fully Qualified Class Name of a class with a zero argument constructor.  This class needs an instance method handle(<code>Throwable</code>) that does your work.  The return type doesn\'t matter, and since a new instance is created every time, don\'t count on keeping state.</p>\n\n<p>So if you don\'t care what thread the exception occurred in a sample may look like this:</p>\n\n<pre><code>class ExceptionHandler implements Thread.UncaughtExceptionHandler {\n  public void uncaughtException(Thread t, Throwable e) {\n    handle(e);\n  }\n\n  public void handle(Throwable throwable) {\n    try {\n      // insert your e-mail code here\n    } catch (Throwable t) {\n      // don\'t let the exception get thrown out, will cause infinite looping!\n    }\n  }\n\n  public static void registerExceptionHandler() {\n    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());\n    System.setProperty("sun.awt.exception.handler", ExceptionHandler.class.getName());\n  }\n}\n</code></pre>\n\n<p>Add this class into some random package, and then call the <code>registerExceptionHandler</code> method and you should be ready to go.</p>\n'}, {'answer_id': 75449, 'author': 'Nik', 'author_id': 13267, 'author_profile': 'https://Stackoverflow.com/users/13267', 'pm_score': 0, 'selected': False, 'text': '<p>Sending an email may not be possible if you are getting a runtime exception like OutOfMemoryError or StackOverflow.  Most likely you will have to spawn another process and catch any exceptions thrown by it (with the various techniques mentioned above).</p>\n'}, {'answer_id': 76614, 'author': 'Alexandre Victoor', 'author_id': 11897, 'author_profile': 'https://Stackoverflow.com/users/11897', 'pm_score': 1, 'selected': False, 'text': '<p>If you are using java 1.3/1.4, Thread.UncaughtExceptionHandler is not available. \nIn this case you can use a solution based on AOP to trigger some code when an exception is thrown. Spring and/or aspectJ might be helpful.</p>\n'}, {'answer_id': 8152499, 'author': 'Alex Fedulov', 'author_id': 336152, 'author_profile': 'https://Stackoverflow.com/users/336152', 'pm_score': 1, 'selected': False, 'text': '<p>In my current project I faced the similar requirement regarding the errors detection. For this purpose I have applied the following approach: I use log4j for logging across my app, and everywhere, where the exception is caught I do the standard thing:  <code>log.error("Error\'s description goes here", e);</code>, where e is the Exception being thrown (see log4j documentation for details regarding the initialization of the "log").\nIn order to detect the error, I use my own Appender, which extends the log4j AppenderSkeleton class:</p>\n\n<pre><code>import org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.spi.LoggingEvent;\n\npublic class ErrorsDetectingAppender extends AppenderSkeleton {\n\n    private static boolean errorsOccured = false;\n\n    public static boolean errorsOccured() {\n        return errorsOccured;\n    }\n\n    public ErrorsDetectingAppender() {\n        super();\n    }\n\n    @Override\n    public void close() {\n        // TODO Auto-generated method stub\n    }\n\n    @Override\n    public boolean requiresLayout() {\n        return false;\n    }\n\n    @Override\n    protected void append(LoggingEvent event) {\n        if (event.getLevel().toString().toLowerCase().equals("error")) {\n            System.out.println("-----------------Errors detected");\n            this.errorsOccured = true;\n        }\n    }\n}\n</code></pre>\n\n<p>The log4j configuration file has to just contain a definition of the new appender and its attachement to the selected logger (root in my case):</p>\n\n<pre><code>log4j.rootLogger = OTHER_APPENDERS, ED\nlog4j.appender.ED=com.your.package.ErrorsDetectingAppender\n</code></pre>\n\n<p>You can either call the errorsOccured() method of the ErrorsDetectingAppender at some significant point in your programs\'s execution flow or react immidiately by adding functionality to the if block in the append() method. This approach is consistent with the semantics: things that you consider errors and log them as such, are detected. If you will later consider selected errors not so important, you just change the logging level to log.warn() and report will not be sent.</p>\n'}, {'answer_id': 57960747, 'author': 'Raedwald', 'author_id': 545127, 'author_profile': 'https://Stackoverflow.com/users/545127', 'pm_score': 0, 'selected': False, 'text': '<p>There is simply no good reason to be informed of every thrown exception. I guess you are assuming that a thrown exception indicates a "problem" that your "need" to know about. But this is wrong. If an exception is thrown, caught and handled, all is well. The only thing you <em>need</em> to be worried about is an exception that is thrown but not handled (not caught). But you can do that in a <code>try</code>...<code>catch</code> clause yourself.</p>\n'}]
['https://Stackoverflow.com/questions/75218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2443/']