2

I was wondering if there was a way to write a catch statement that is activated whenever any exception is thrown in a program. Thanks!

nrubin29
  • 1,522
  • 5
  • 25
  • 53
  • Taken literally, it is impossible, because the exception may have been caught close to the point it was thrown. The best you can do is catch all exceptions that are not otherwise caught, as described in @assylias answer. – Patricia Shanahan Apr 11 '13 at 22:57

5 Answers5

14

The problem with the answers you have received so far is that if you include a "catch-all" in your main, it will only catch exceptions thrown on the main thread.

A more robust way to catch all uncaught exceptions is to setup a DefaultUncaughtExceptionHandler for your project, for example, at the start of your main, you can call:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        //log the exception
    }
});

Note that it is generally unreasonable to do anything but logging in there, as the Throwable could be anything, including unrecoverable errors.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Very interesting. I was completely unaware of that possibility. – Steve Kallestad Apr 11 '13 at 22:54
  • Thanks, that's exactly what I was looking for! I'm going to use it so that whenever an error occurs, it'll send the error in an email to me. – nrubin29 Apr 11 '13 at 23:21
  • aww...! that almost worked!, I needed to trap NPE, but the library implemented ExecutionException (that seems to trap NPE) and so that didnt work :(, will keep for all other cases thx! – Aquarius Power Jan 19 '16 at 02:09
  • 1
    @AquariusPower There is no reason why it would not work - my guess is that you caught the `ExecutionException` in your code without looking at what caused it with `e.getCause()` (which would be the NPE). So in fact you *are* catching the exception - but ignoring it - and the uncaught exception handler is not called. – assylias Jan 20 '16 at 12:14
2

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself) From How can I catch all the exceptions that will be thrown through reading and writing a file?

try {

    // exceptional block of code ...
    // ...
} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.
}

The reason that works is because Exception is the base class for all runtime exceptions. Thus any runtime exception that may get thrown is an Exception.

The is because all runtime exceptions inherit from Exception. Note that there is a difference between an Error and Exception Unchecked exceptions in Java: Inherit from Error or RuntimeException?, In that case you may need to do:

try {

} catch(Throwable e) {

}

See this When should Throwable be used instead of new Exception?. One user notes:

Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be catched as well. See comments for additional information.

Community
  • 1
  • 1
Anil Vaitla
  • 2,958
  • 22
  • 31
  • 1
    It should be noted that simply try/catching everything in Main won't necessarily hide all errors from the end user. Any of the libraries you reference can have their own exception handling in place, and they won't necessarily bubble up all of their exceptions. The libraries themselves can choose to ignore exceptions, present stack traces to the end user, log things to file, etc. – Steve Kallestad Apr 11 '13 at 22:26
  • 1
    That will only catch exceptions thrown by the current thread. – assylias Apr 11 '13 at 22:36
  • @assylias Good point, if he is making child threads, would he need to follow this (see first answer) http://stackoverflow.com/questions/2631791/java-handling-exceptions-in-child-threads. Or is there a better way? – Anil Vaitla Apr 11 '13 at 22:40
  • @tigger I have added an answer. – assylias Apr 11 '13 at 22:41
2

You can make the type Exception. That will catch any Exception, but it also doesn't give the programmer much information on what went wrong. It's usually better to try to be more specific about the type of exception that has occurred, mainly for semantic reasons.

The theory

Every type of Java Exception extends the Exception type. Because Exception is a superclass of all exceptions, when an exception is thrown, regardless of it's type, it can still be implicitly casted to an object of type Exception.

Edit

As mentioned in the comments, there is also type Error that can be thrown, so to really catch everything using the Throwable type is best. Throwable is more general than Exception, but it still works on the exact same principle. It is the superclass of anything that can be thrown.

For Example

try{
   // Some code
}
catch(Throwable e)
{
    // Do something. Edited due to comment!
}
christopher
  • 26,815
  • 5
  • 55
  • 89
0

Yes, any error that falls through will be caught by this:

try {
    //do things here
} catch (Exception e) {
    //handle exception here
}

Note, however, that it's typically the wrong thing to do.

raptortech97
  • 507
  • 3
  • 14
0

In your main, put all your code in

try {
    //Your code
} catch(Exception e) {
    //Handle exceptions 
}

This will handle any exception invoked by your code.