one : When an exception may be encountered in the code, you need to use the try{ }catch{Exception e} To handle , Otherwise, the program will crash

try{

int i = 1/0;

}catch(Exception e){

........

}

two : Don't for Nested inside loop try catch clause

for (int i = 0; i < array.length; i++) {

try {

.......

} catch (IOException e) {

.......

} catch (Exception e) {

.......

}

}

Change to :

try {

for (int i = 0; i < array.length; i++) {

.......

}

} catch (IOException e) {

.......

} catch (Exception e) {

.......

}

three : Minimize try catch Nesting of clauses , Will affect performance

try {

try {

.......

} catch (IOException e) {

.......

}

} catch (Exception e) {

.......

}

Change to

try {

.......

}catch (IOException e) {

.......

} catch (Exception e) {

.......

}

four : Same try Multiple in Clause catch Hour , Exception handling principle

When a try Block contains numerous statements , Many different exceptions may be thrown , Only through multiple catch Block to catch different exceptions . If there is an inheritance relationship between two exceptions , You should catch subclass exceptions before your parent exceptions , Or put the minimum range exception first
, Wide range put in the back , Because according to catch Block matching from top to bottom , When it matches a catch Block time , He went straight into this catch In the block , There's more in the back catch Block words , It does nothing , Jump straight over , Ignore all . If any finally Enter finally Go ahead inside .Exception The root class of this exception must just be in the last catch inside , If placed in the front or middle , Any exceptions will be associated with Exception Matched , It will be reported that it has been captured ... Unexpected error . Simultaneous coordination log4j It will be very helpful for the future maintenance of the program .

try {

.......

}catch (IOException e) {

.......

} catch (Exception e) {

.......

}

Technology