TheFrancisOne TheFrancisOne - 1 month ago 21
Java Question

Java try catch blocks

Here a simple question :

What do you think of code which use try catch for every instruction ?

void myfunction() {
try {
instruction1();
}
catch (ExceptionType1 e) {
// some code
}
try {
instruction2();
}
catch (ExceptionType2 e) {
// some code
}
try {
instruction3();
}
catch (ExceptionType3 e) {
// some code
}
try {
instruction4();
}
catch (ExceptionType4 e) {
// some code
}

// etc
}


I know that's horrible, but I want to know if that decreases performance.

Answer

Try something like this: (I know this doesn't answer your question, but it's cleaner)

void myfunction() {
try {
    instruction1();
    instruction2();
    instruction3();
    instruction4();
}
catch (ExceptionType1 e) {
    // some code
}
catch (ExceptionType2 e) {
    // some code
}
catch (ExceptionType3 e) {
    // some code
}
catch (ExceptionType4 e) {
    // some code
}

// etc
}