JavaRush /Java Blog /Random EN /Loop for try-catch
dimaMJ
Level 25
Craiova

Loop for try-catch

Published in the Random EN group
The program is simple, the user enters the file name, if such a file exists, it is read, etc., if not, then an exception is triggered and the user must enter the file name again, and so on until the file name is correct. Here is the code: public class Solution { public static void main(String[] args) throws Exception { InputStream inStream = filego(); OutputStream outStream = new PrintStream(System.out); while(inStream.available()>0) { int data = inStream.read(); outStream.write(data); } inStream.close(); outStream.close(); } public static InputStream filego() throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String FileName = reader.readLine(); InputStream inStream = null ; try { inStream = new FileInputStream(FileName); } catch (Exception e) { System.out.println("Файл не найден, введите еще раз"); filego(); } return inStream; } } When starting the program, when I enter the wrong name, everything works, when I enter the correct one, it throws Exception in thread "main" java.lang.NullPointerException, that is, for some reason it returns null, what am I doing wrong, maybe my eyes are fogged up or something is wrong I understand, please tell me) I really want to figure out how to correctly make a try-catch loop. I tried it without a separate method, just using while, nothing good came out either)
And did I specify the type of the return value correctly?
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION