Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happen to the exceptions when try used the finally only instead of catch and how it handles? [duplicate]

when a programmer use a try block without catch

like this

    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        pm.makePersistent(c);
    } finally {
        pm.close();
    }

what happen to exception and how it possibly handle later ?

I try learn it from internet but no clear result for it...

like image 546
Krishna Avatar asked Sep 26 '14 07:09

Krishna


People also ask

What happens if you exclude catch and use only try and finally?

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. exit() it will execute always.

What happens to exception in try finally?

An exception occurring in finally block behaves in the same way as any other exception. Even if the try block contains a return statement or branching statements like break and continue, then the finally block will still be executed.

What happens if a try catch finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

Once catch block finished execution then finally block and after that rest of the program. If there is no exception occurred in the code which is present in try block then first, the try block gets executed completely and then control gets transferred to finally block (skipping catch blocks).

What happens if an exception is not caught in a method?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.


1 Answers

When you do not specify a catch block you are basically moving the responsibility of handling the exception to the caller of the method.

So if your method does not catch one or more Exceptions from the try block and an exception is raised in your method block it will be thrown back to the caller.

The finally block ensures that if something bad happens in the try block then at least you will have a chance to close/release any resources related before the exception is thrown back to the caller.

like image 133
giorashc Avatar answered Sep 28 '22 06:09

giorashc