1

I have written a function as below, In try block I am throwing IOException which is handled by next catch block and its again throwing FileNotFoundException, In the finally block I again throw a NULLPointerException. so my question is FileNotFOundException exception is unhandled exception? why the caller function only get NULLPointerException only,Although FileNotFounException is unhandled(what I am assuming)?

static void fun(){
        try{
            throw new IOException();
        }
        catch(IOException e){
            throw new FileNotFoundException();
        }
        finally{
            throw new NullPointerException();
        }
    }
dead programmer
  • 4,223
  • 9
  • 46
  • 77

3 Answers3

0

You can only throw one exception at a time unless you're wrapping old ones inside of new ones. Finally is last so it wins.

Since you're obviously not posting working code but code meant to explore this issue and demonstrate behavior I won't bother correcting you. I will point you to some code that deals with a very real problem that follows from this issue.

The problem comes up when you try to close something in finally and the close method itself throws an exception. You end up needing a second try.

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62
0

You aren't using the finally statement correctly.

According to the Java docs:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

So, yes, you do have an unhandled exception. If you are trying to handle multiple errors, I'd throw exceptions, rather than using a try/catch like this:

static void fun() throws FileNotFoundException, NullPointerException{
   //your code here

}

Then when you call the method, you can surround that in a try/catch:

    try{
       YourClass.fun();
    }catch(Exception e){
       //handle the error.
    }finally{
       //clean up code, this is optional
    }
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
-1

Yes, FileNotFoundException is unhandled. To handle it, surround fun() with another trycatch block.

try{
  fun();
catch(FileNotFoundException ex){
}
catch(NullPointerException ex){
}
Quicksilver002
  • 735
  • 5
  • 12