141

In Java, is there any way to get (catch) all exceptions instead of catching the exceptions individually?

2
  • 3
    and I will catch all those specific Exceptions with catch(Exception e){}??
    – Johanna
    Commented Jul 2, 2009 at 18:21
  • 1
    yeah. Since Exception is the base class of all exceptions, it will catch any exception.
    – jjnguy
    Commented Jul 2, 2009 at 18:23

7 Answers 7

133

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

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 exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}
107

While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

try{
    // IO code
} catch (Exception e){
    if(e instanceof IOException){
        // handle this exception type
    } else if (e instanceof AnotherExceptionType){
        //handle this one
    } else {
        // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
        throw e;
    }
}

However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

try{
    // IO code
} catch (Throwable t){
    if(t instanceof Exception){
        if(t instanceof IOException){
            // handle this exception type
        } else if (t instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else if (t instanceof Error){
        if(t instanceof IOError){
            // handle this Error
        } else if (t instanceof AnotherError){
            //handle different Error
        } else {
            // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else {
        // This should never be reached, unless you have subclassed Throwable for your own purposes.
        throw t;
    }
}
6
  • 2
    I would argue that you should catch each exception explicitly, but the question explicitly asked how to catch everything a block of code would throw.
    – codethulhu
    Commented Feb 17, 2014 at 16:15
  • 1
    That throwable was useful.
    – Anshul
    Commented May 21, 2014 at 7:21
  • This is the solution I was looking for, I needed an if else for exception handling. Thanks
    – CubeJockey
    Commented Jul 23, 2015 at 14:49
  • 2
    Throwable tip is really useful. Commented Jun 16, 2017 at 20:51
  • If you catch Throwables you should keep in mind that the VirtualMachineErrors such as StackOverflowError or OutOfMemoryError does not allow you to do much more than logging. They are outside of the applications control and you can not handle them.
    – Datz
    Commented Apr 16, 2019 at 5:28
16

Catch the base exception 'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }
7
  • 11
    If you write this code, you are almost certainly doing something terribly wrong.
    – George
    Commented May 2, 2013 at 3:40
  • 2
    @George Why did you say that?
    – kuchi
    Commented Jun 20, 2013 at 17:24
  • 14
    @George Not necessarily, if you deal with something that has a lot of sensitive entry parameters and it is very complicated to verify the validity of each one of them, catching all kind of exceptions once the working cases are properly tested is the way to go. It will make the code clear and way less mindf*k than a huge and potentially heavy condition.
    – Johnride
    Commented Nov 15, 2013 at 18:53
  • 4
    Most coders I have worked with put nothing in their catch statements, so using this try catch snippet is actually better than catching a bunch of different exception types and not doing anything with it
    – Lou Morda
    Commented Apr 6, 2015 at 23:56
  • 1
    @LouisMorda I disagree, catching every Exception subclass and not doing anything based on them (ignoring them) is worse than only catching some specific exceptions and ignoring them. If you catch some Exception types and don't do anything with the information, you have no chance of knowing what went wrong in those situations, but if you catch all Exception subclasses you have no chance of knowing what went wrong in a much large number of situations. Consider how you would handle bug reports without the information from the exceptions, like stacktraces and messages.
    – zpon
    Commented Jul 29, 2015 at 12:29
10

You may catch multiple exceptions in single catch block.

try{
  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.
} 
7

It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.

For most file operations, IOException is the root exception. Better to catch that, instead.

1
  • 2
    It is bad practice to catch Exception. why? downvote bad explained Commented Mar 22, 2018 at 17:38
7

Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?

If so:

try {
   //...file IO...
} catch(Exception e) {
   //...do stuff with e, such as check its type or log it...
}
2
  • What should I do for the ones that are not specific??
    – Johanna
    Commented Jul 2, 2009 at 18:20
  • and I will catch all those specific Exceptions with catch(Exception e){}??
    – Johanna
    Commented Jul 2, 2009 at 18:20
4

Yes there is.

try
{
    //Read/write file
}catch(Exception ex)
{
    //catches all exceptions extended from Exception (which is everything)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.