1

I have my code block here. It tells me the IOException is unhandled.

public static void main(String[] args) {
        FileWriter locFile = null;              
        try{                                  
            locFile = new FileWriter("locFile.txt");
            for(Location location : locations.values()){
                locFile.write(location.getLocationID()+", "+location.getDescription()+"\n");
            }
        }catch(IOException e){                     
            throw new IOException("My message");
            e.printStackTrace();
        }finally{
            try{
                if(locFile != null){
                    System.out.println("Attempting to close locFile");
                    locFile.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

I think one way I can do is like this:

public static void main(String[] args) throws IOException{
   ...
}

But can I throw the exception inside the catch block? Is it practical or common to do so?

Steven
  • 61
  • 2
  • 6
  • why throw an exception here `throw new IOException("My message");` - nothing can handle it, so why not just print a message and quit? – Scary Wombat May 07 '18 at 02:31
  • 1
    Why are you re-throwing a new IOException in the catch block? Either you want to deal with it or you want to let it propagate up (through throws) – Charles Shiller May 07 '18 at 02:31
  • The catch block protects the code in the `try` block only. Whatever exceptions (can) get thrown inside the catch block is not protected by the preceding try block and it's perfectly alright to throw an IOException there. What can happen there is some check on the exact IO exception, or perhaps on how many times you've already caught it (as part of some retry-mechanism) and only throw the IOException when some conditions are met. – Erwin Bolwidt May 07 '18 at 02:34
  • You have to *handle* an exception. Putting up a *catch* that *throws* again is **not** handling. That is like a NO OP (like not writing that catch in the first place). That is all there is to this. – GhostCat May 07 '18 at 02:42

1 Answers1

0

If you remove the following call to throw then your code runs fine for me:

throw new IOException("My message");

If you do want to rethrow IOException, then you would need to mark your main() method as throwing an exception, e.g.

public static void main(String[] args) throws IOException

There are scenarios where you would want to do something like this. But more typically, what I have seen/done is that if a method throws an exception, you might not bother to catch anything inside that method.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360