I want to create a java Printwriter object that any method in my program can use. I tried creating a static Printwriter object outside of any of the methods (if I create it inside of a method, it can only be used inside that method), however, in order to create a Printwriter object, I need to throw an IOException inside the method head and if I'm not creating the object inside of a method, there isn't any method head to throw the exception from. I've tried googling how to do it 5 billion times so if anyone can help, that'd be great. Thank you!
This should work:
public class WriterHolder {
public final static PrintWriter GLOBAL_WRITER = createWriter();
private static PrintWriter createWriter() throws IOException {
... create and return that writer
You see - declaring that your method can throw an exception is just an indication that this might happen at runtime. That doesn't prevent you from simply calling that method?! Of course, the thing is: when that exception gets thrown at runtime, your program will fail immediately. But given the fact that this writer object seems to be so important to your code, that seems like the right thing to do.
But also note: introducing such global state via a shared object is considered bad practice. I would rather recommend to step back and try to find a design that doesn't impose such consequences on you.