5

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...

Krishna
  • 59
  • 1
  • 1
  • 7

5 Answers5

1

Yes. It makes sense. In your case even exception comes, the programmer want to just ignore the exception throwed and close the PersistenceManager. At this level the exception ignored and at top level some one may catch that. It delegates to there.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

catch statement is used to catch the specific exception based on your need. Even you can use general exception in catch to catch the exception. If you use without catch exception will be handled by default.

Shriram
  • 4,343
  • 8
  • 37
  • 64
1

At that point the exception is not handled and will still bubble up. It iwll have to be handled later

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1

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.

giorashc
  • 13,691
  • 3
  • 35
  • 71
1

This is a common idiom for handling (or better: not handling) exceptions in code that is allocating resources.

If an exception occurs in a try block, this block will end abruptly. Then a corresponding catch statement will be looked up. If this is not found than the outer block will end abruptly, which most of the times means that the method will throw this exception to its caller.

But before that a finally block will always be executed after leaving the try block (and even after handling a caught exception). This is the best place to dispose any allocated resources. In that way you make sure that you clean up after your work, whether an exception occurred or not.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66