JAVA + try catch (FileNotFoundException e) occurs in catch (Exception e)?

I have a command that creates a file on disk. Since the folder in which the file is to be created is dynamic, I have a catch (FileNotFoundException e). In the same try block, I already have a catch block (Exception e). For some reason, when I run my code and the folder does not exist yet, the catch block (Exception e) is used, not the FileNotFoundException file.

The debugger is clear though (at least for me), showing FileNotFoundException: java.io.FileNotFoundException: c: \ mydata \ 2F8890C2-13B9-4D65-987D-5F447FF0DDA7 \ filename.png (the system cannot find the path specified)

Any idea why it is not included in the FileNotFoundException block? Thanks;

CODE:

import java.io.FileNotFoundException; try{ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(screenRectangle); ImageIO.write(image, "png", new File(fileName)); } catch (FileNotFoundException e){ // do stuff here.. return false; } catch(Exception e){ // do stuff here.. return = false; } 
+6
source share
2 answers

It is also possible that the particular problem you are facing is not an exception to FileNotFoundException. Using the “Exception” in the catch block (which is the parent class for all Exceptions), it will actually “catch everything” because it will be executed if the “Exception” or any of its subclasses exists.

Try the following change:

 ... catch (Exception e) { System.out.println(e.getClass()); } ... 

This will tell you which particular Exception class falls into this block. I bet you'll find that Exception is actually an instance of a subclass (e.g., IOException, for example).

+4
source

Your problem is that a FileNotFoundException is thrown somewhere deep inside the java library and is not propagated, so you cannot catch it. The real culprit here is the NullPointerException that comes from

 ImageIO.write(image, "png", new File(fileName)); 

call. This run is part of your catch (Exception e) block.
If you add a catch (NullPointerException e) before your general Exception output, you will see that it is there.

0
source

Source: https://habr.com/ru/post/887369/


All Articles