Always contruct try-catch blocks in a way that assumes catching Exceptions from more detailed to more generic.
Example
try { String [] tab = null; System.out.println(tab[3]); } catch (Exception e) { System.out.println("Exception"); } catch (NullPointerException e) { System.out.println("NullPointerException"); }
The above presented snippet will cause compilation error:
Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception
Solution
try { String [] tab = null; System.out.println(tab[3]); } catch (NullPointerException e) { System.out.println("NullPointerException"); } catch (Exception e) { System.out.println("Exception"); }
This way, if you invoke this snippet you’ll get the following output on the screen: “NullPointerException”.