Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try catch blocks

Tags:

java

try-catch

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.

like image 629
TheFrancisOne Avatar asked Mar 01 '11 18:03

TheFrancisOne


People also ask

Does a try block need a catch block Java?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.

Can Java have multiple try catch blocks?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.

What are try catch blocks?

What Does Try/Catch Block Mean? "Try" and "catch" are keywords that represent the handling of exceptions due to data or coding errors during program execution. A try block is the block of code in which exceptions occur. A catch block catches and handles try block exceptions.

What are try catch blocks in Java?

The Try Block of Try Catch in Java A try block is the block of code (contains a set of statements) in which exceptions can occur; it's used to enclose the code that might throw an exception. The try block is always followed by a catch block, which handles the exception that occurs in the associated try block.


1 Answers

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
}
like image 60
Richard Pianka Avatar answered Oct 01 '22 21:10

Richard Pianka