Execution flow of a try / catch / finally block

5

How does the execution flow in a try/catch/finally block work in the example below?

public class ExceptionTest {

    public static void makeException() throws ExceptionAlpha, ExceptionBeta, ExceptionGamma {

        throw new ExceptionBeta();    

    }

    public static void main(String [] args) {

        try {

            makeException();
            System.out.println("Isto não vai ser executado.");

        } catch(ExceptionAlpha alphaEx) {

            System.out.println("Exceção Alpha foi lançada.");

        } catch(ExceptionBeta betaEx) {

            System.out.println("Exceção Beta foi lançada.");

        } catch(ExceptionGamma gammaEx) {

            System.out.println("Exceção Gamma foi lançada.");

        } finally {

            System.out.println("Isto será executado, independente se houver exceções.");

        }

    }

}

Is it possible to use logical operators in catch? for example: catch(ExceptionAlpha alphaEx && ExceptionBeta betaEx) {...}

I also wanted to know, in this same code, how to make more than one exception, in addition to ExceptionBeta and how the code execution flow would be.

Thank you!

    
asked by anonymous 02.08.2014 / 18:40

1 answer

6
  

How does the execution flow in a try / catch / finally block work in the example below?

You will enter the try and throw an exception. As expected, println after makeException() will not run. After that, program will execute block catch(ExceptionBeta and after that the block inside finally .

The finally block always executes at the end, regardless of whether an exception has been thrown or not (it is particularly useful for cleaning at the end of the method)

  

I also wanted to know in this code how to launch more than one exception, in addition to ExceptionBeta

In Java, and in all programming languages I know of with exceptions, you can only throw one exception at a time.

One possibility is to create a single class for the exception and pass the error list as one of the fields of that class.

  

Is it possible to use logical operators in catch? for example: catch (ExceptionAlpha alphaEx & ExceptionBeta betaEx) {...}

I do not know what you expect & amp; do in that case. Anyway, I do not think Java supports anything like that.

As for "or", to handle more than one exception type in a single catch, in Java 7+ there is the | syntax for this:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

link

If you are with an older version of Java, the best you can do is to catch a superclass of your classes or make several catchs yourself. In the latter case you can try to create an internal medotozinho to avoid duplicating code.

} catch(ExceptionAlpha alphaEx) { 
    tratarExcecao();
} catch(ExceptionBeta betaEx) {
    tratarExcecao();
}
    
02.08.2014 / 19:19