Well, the name of the question says it all.
I have some points to make before submitting the code:
- If I know that a particular type of exception occurs in a particular set of statements, then should I use them in one attempt to immediately put the appropriate catch?
Or should I put all the error-prone code in one block of code and put all the corresponding catch blocks after this single attempt. Are there any performance costs associated with this?
{ try { exec();//can cause ExceptionXYZ } catch(ExceptionXYZ e){ } try { exec(); //can cause ExceptionPQR } catch(ExceptionPQR e){ } try { exec(); //can cause ExceptionABC } catch(ExceptionABC e){ } }
Thus, the above method is good or lower than one
{ try { exec(); //can cause ExceptionXYZ exec(); // can cause ExceptionPQR exec(); //can cause ExceptionABC } catch(ExceptionXYZ e){ } catch(ExceptionPQR e){ } catch(ExceptionABC e){ } }
It may also be possible to mix over two patterns, for example, nesting try in try . Any other considerations / points to be used when? . One thing is making sure that nesting complicates the code a bit.
In other scenarios, for example, when shutting down JDBC database resources, there are several other considerations (in the section ) in which we should handle each closure independently to ensure that one-way NullPointerException does not leave open resources:
try { } catch(Exception e) { } finally { if (rs != null) //ResultSet try { rs.close(); } catch(SQLException se1) { se1.printStackTrace(); } if(pstmt!=null) //PreparedStatement try { pstmt.close(); } catch(SQLException se2) { se2.printStackTrace(); } if(conn!=null) //Connection try { conn.close(); } catch (SQLException se3) { se3.printStackTrace(); } }
Any thoughts? Or just thinking too much.
Edit
Some additional considerations / facts (above thinking: p)
Just generalizing things: If at all there are some blocks of code, all of which must be executed in any case, then we should put them on a separate try-catch and any other code from these catch blocks should not cause any exceptions:
{ try { mustexec(); } catch(){ } noexceptionexec(); try { mustexec(); } catch() { } }
Providing the smallest drop through catch () . If we are sure that a certain set of statements can cause a specific set of Exception, we should put these lines of code in the handler of the corresponding Exception instead of throwing it after an external attempt. Thus, above the third case (mix pattern) may be appropriate:
{ try { exec(); //can cause ExceptionXYZ } catch(ExceptionABC){ } catch(ExceptionPQR){ } catch(ExceptionXYZ){ } }
Higher may be slightly inefficient than
{ try { try { exec(); //can cause ExceptionXYZ } catch(ExceptionXYZ){ } } catch(ExceptionABC){ } catch(ExceptionPQR){ } }
source share