简体   繁体   中英

When to consider catching Specific Exceptions Vs General Exception in Java

Catching specific exceptions like option 1 below is very common and also considered the save way to catch exceptions, Why the option 2 is rarely considered because of how verbose(not sure if that's the word to use!) it can become, that's what I understand so far. My question is that are there any other instances when one should consider catching exceptions like option 2(General Exception) rather than Option 1 ?

Opt1 -> Specific Exceptions:

try{
    TextIO.putf(s);
    FileOutputStream mFileOutputStream = new FileOutputStream("/content/doc/test.pdf", true);
}catch (FileNotFoundException notfEx){
       //Do something
}catch (NullPointerException nullEx){
       //Do something
}catch(IllegalArgumentException illEx){
       //Do something
}

Opt2 -> General Exception:

try{
    TextIO.putf(s);
    FileOutputStream mFileOutputStream = new FileOutputStream("/content/doc/test.pdf", true);
   }catch (Exception ex){                
    if(ex.getClass() == java.io.FileNotFoundException.class) {
      //Do something
    }else if(ex.getClass() == java.lang.IllegalArgumentException.class){
      //Do something
    }else if(ex.getClass() == java.lang.NullPointerException.class){
      //Do something
    }
  }
}

You are simply asking the wrong question, a typical example of pre-mature optimisation.

The (potentially nil) difference in performance between your two options does not matter at all.

Keep in mind: you are talking about dealing with an exception that was just thrown. Rest assured: creating that exception, and collecting its stack trace is thousands of times more expensive compared to some hypothetical gain because of using your options 1 or 2.

Thus: you can safely ignore performance here. You simply do what is easier to read, and easier to understand for human readers of your code. Which of course dictates to use version 1. And as the comments are pointing out: actually, your option 2 isn't equivalent to option 1 (as it ignores sub classes of exceptions). So, not only is that option 2 way harder to read and maintain, it is also very likely to result in unexpected (wrong) exception handling.

Finally: you are also victim of another common problem with newbie Java programmers. They assume that "what you do in source java" is the relevant factor for java performance at runtime. But that is not true. The real performance of java comes out of the JIT, and its efforts to compile java byte code into machine code. You have to make sure that the JIT can do a good job (and of course: to avoid stupid mistakes within your code). So again: your ideas do not contribute anything meaningful to "how to achieve performance".

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