we know that a class will compile if no catch along with try but have finally but what happens if there is an arithmetic exception in the try block????

Dani AI

Generated

Short answer for : Java permits a try with no catch as long as there is a finally. If an ArithmeticException (an unchecked RuntimeException) is thrown inside the try, the finally block runs before the method exits, and then the exception is propagated to the caller — unless the finally itself changes control flow.

Example (illustrates propagation):

try {
    int x = 1 / 0;   // ArithmeticException
} finally {
    System.out.println("cleanup");
}
// the ArithmeticException is rethrown after "cleanup" prints

Two important caveats to add to what said:

  • If the finally block throws another exception or executes a return, that new action replaces (hides) the original ArithmeticException. Hiding exceptions from finally is a common source of bugs.
  • finally will not run if the JVM is forcibly terminated (for example, System.exit or the process is killed). Normal thread interruption does not prevent finally from executing.

Best practice: perform only cleanup in finally (close resources, restore state), avoid return or throwing new exceptions there, and catch and handle specific exceptions (e.g., catch ArithmeticException if it should be recovered from). For authoritative details see the Java tutorial on finally: The finally block.

Note to thread: 's tone is unhelpful, and 's moderation point about post dates is valid — clarifications like this are intended to make the behavior explicit and show the edge cases.

Recommended Answers

All 3 Replies

try and see for yourself.
You're annoying with your flooding of this place with stupid "questions" that show only that you have no clue whatsoever about anything.

it works fine. even if any kind exception is raised at runtime the finally() method will be called irrespective of what kind of exception it thrown.

Hey there satya5321,

You have answered a couple of threads in the Java forum today that have already been fairly well finished and are over three weeks old. Please check the date of the last post before replying to a thread.

Cheers,
darkagn

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.