-1

I created a method that accepts an IOException as an argument. This method opens the out stream and prints information about the exception to a text file. My problem that I seem to be running into.. How to call that method from a catch block?

try{
    if(true)
        throw new IOException();
}
catch(IOException e){
    //pass it to a method
}

:::EDIT:::

public void logErrors(IOException e){
    PrintWriter out = yada yada;

    out.println(e.getCause());
}
Podis
  • 379
  • 2
  • 17
  • it is simply `yourMethod(e);` – Leah Aug 30 '15 at 18:52
  • callthemethodyouwant(e); – Kaushik Sivakumar Aug 30 '15 at 18:53
  • If you're getting an IOException you probably shouldn't be trying to use an out stream after catching it, because that's what might have caused the error in the first place. – Zarwan Aug 30 '15 at 18:53
  • Why do this? Why catch the same exception that you're throwing within this short piece of code? Why not simply do: `if (...) { myMethod(); }` and leave exceptions out of this? – Hovercraft Full Of Eels Aug 30 '15 at 18:54
  • @Leah, I tried.. it says "unreported exception... must be thrown or caught" – Podis Aug 30 '15 at 18:55
  • @Zar, You might be right.. opening the stream within that method does throw another IOException.. Perhaps the problem lies within my method.. – Podis Aug 30 '15 at 18:56
  • I suspect you've invented a bicycle :) Use logger, [for instance slf4j](http://www.slf4j.org/). There are methods to log exceptions. –  Aug 30 '15 at 18:57
  • @Podis .Can you post the whole method if possible.It might be similar to http://stackoverflow.com/questions/8707906/unreported-exception-java-io-ioexception-must-be-caught-or-declared-to-be-throw – Kaushik Sivakumar Aug 30 '15 at 18:58
  • You are getting yourself into a loop. Every time you try to use an output stream you have to catch an IOException, and if you try to log that error in a file you're back where you started. Like Rafael said, you might want to reconsider how you log your errors. – Zarwan Aug 30 '15 at 19:00
  • So.. Thanks to everyone for the help. It was a little confusing because I missed that NetBeans auto-implemented a throws clause in there.. just one of those overlooked things. It's working now =) – Podis Aug 31 '15 at 11:03

1 Answers1

0

Basically you just have to call the name of the method, where you want the method's code to be executed like this:

try{
    if(true)
        throw new IOException();
}
catch(IOException e){
    //pass it to a method
    methodToExecute(e);
}

also, I can see that you throw an IOException in both cases so perhaps 
you may want to consider modifying the code to use a finally block

EDIT

On second thought, you can just use an if statement to throw it always.

if (...)
{
   yourMethod(throw new IOException());
}
Mechanic
  • 172
  • 1
  • 10