@Override String toHex(String filepath) { try { FileReader readFile = new FileReader(filepath); BufferedReader readBuffer = new BufferedReader(readFile); } catch (IOException error) { System.out.println("Input output error: " + error); } return null; } 

There is such a block of code, I understand at this stage it looks senseless, but the question arose precisely in it. I understand the question may seem extremely trivial, but how to use readFile or readBuffer outside the try...catch ?
UPD: without using throws

  • 2
    FileReader readFile = null; try { ... } catch { ... } readFile.doSomething(); - ArchDemon

2 answers 2

And why are you going to use code with a potential exception outside the try / catch structure? At a minimum, you will have an overly bulky code where it is completely unnecessary.

Here, in my opinion, optimum use of the code given by you.

 @Override String toHex(String filepath) { try (BufferedReader readBuffer = new BufferedReader(new FileReader(filepath))) { return readBuffer.toString(); } catch (Exception error) { System.out.println("Error while loading file: " + error); return null; } } 

And do not use specific exception instances where you are not sure about the exception. As a result, with your IOException, you will break your head after trying to understand why the code does not work, if the exception is different due to incorrect processing logic inside the structure.

    №1

    use throws IOException when creating a method

     public void my_coord(String Coord) throws IOException { FileOutputStream fos = openFileOutput("coord.txt", MODE_PRIVATE); BufferedReader bf = new BufferedReader(new InputStreamReader(openFileInput("coord.txt"))); 

    No. 2 is not quite, without try, but without catch

     public void inz(String name) throws IOException { OutputStream os = null; try { os = openFileOutput(name, MODE_PRIVATE); } finally { os.close(); } } 

    working with writing-reading, you cannot completely give up try-catch. Either you specify this when creating a method, or in its "internals"