0

Why here I've got only RuntimeException("in finally") but no NullpointerException("in catch")? And if I comment // throw new NullPointerException("in finally"); in finally block why I would get NullPointerException("in catch")? What's going on here?

public class Solution
{
    public static void main(String[] args)
    {
        try
        {
            throw new ArithmeticException();
        }
        catch (ArithmeticException e)
        {
            throw new NullPointerException("in catch");
        }
        finally
        {
            throw new RuntimeException("in finally");
        }
    }
}
Denys_newbie
  • 1,140
  • 5
  • 15
  • 1
    `finally` beats everything (except for `System.exit(...)`). Try calling this method, the returned value may surprise you: `public static int foo() { try { return 1; } finally { return 5; } }`. The code presented follows the same principle (i.e. the `Exception` from the `catch`-block is lost, the `Exception` from the `finally`-block is thrown). – Turing85 Apr 22 '21 at 20:50
  • 1
    Because the `finally` block is **always** getting executed and if you `return` or `throw` something there you overwrite the previous `throw` or `return` - that is why you should really not `throw` or `return` in `finally`. And regarding why you get "only" one exception - because there is no system in place to throw two exceptions or return two different values, you either get this exception or that or return this value or that, but you cannot throw two exceptions at once (you can nest exceptions but that is a different topic). – luk2302 Apr 22 '21 at 20:50

0 Answers0