Home > Software engineering >  How finally block works?
How finally block works?

Time:09-15

hello community in my tutorial this week I found out that all threads stop when java gets a runtime error, but in the finally code block this event looks a bit strange.

public class main {
  public static void main(String[] args) {

    try {
        Scanner kb = new Scanner(System.in);

        System.out.println("enter number:");
        double val = Double.parseDouble(kb.nextLine());
        double result = MathUtil.myLog(val);
    }
    catch (MyException ex) {
        System.out.println("Cath:foo");
    }
    finally {
        System.out.println("foo:finally");
    }
}

class MathUtil {
  public static double myLog(double val)
{
    if (val < 0)
        throw new MyException();

    if(val == 0)
        throw new YourException();

    return Math.log(val);
}
class MyException extends RuntimeException {

}

class YourException extends RuntimeException {

}

When i execute this code and make an incorrect entry it first executes the finally block and then I get runtimeError.

CodePudding user response:

Works as indented, doesn't matter if catch clause catch an error, finally as it says will execute almost every time. It won't execute only if JVM runs out of memory but it's rare corner case

CodePudding user response:

This works as designed :-) From the documantation from oracle: 'The finally block always executes when the try block exits..' For me this means the finally block will be executed before the catch block or anything else is executed.

  • Related