Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This construction is illegal, as you have discovered. Members whose constructors throw checked exceptions cannot be constructed except when in a context that allows exception handling, such as a constructor, an instance initializer, or (for a static member) a static initializer.</p> <p>So this would be a legal way to do it:</p> <pre><code>public class MyClass { MyFileWriter x; { try { x = new MyFileWriter("foo.txt"); } catch (IOException ex) { ex.printStackTrace(); } } ... } </code></pre> <p>Legal, but rather ugly. I would prefer either initializing it in the constructor and declaring the exception there, or else making the user call a method to explicitly initialize it. But if the user must initialize it, you must then account in any dependent methods for the possibility of the object's being invalid.</p> <p>If you are writing <code>MyClass</code> as a wrapper for <code>MyFileWriter</code>, I would say to do the initialization in the constructor. Otherwise, I would first question whether it is necessary to have a writer open during the object's entire lifetime. It may be possible to refactor this away.</p> <p><strong>Edit:</strong> When I was writing this, the "<code>static</code>" hadn't been added to the field. This changes things quite a bit: I now would like to know why on earth you want to have a writer open for the <em>classloader's</em> entire lifetime. How could it ever be closed?</p> <p>Is this a home-grown logging system of some sort? If so, I'd encourage you to have a look at <a href="http://java.sun.com/javase/6/docs/api/java/util/logging/package-summary.html" rel="nofollow noreferrer"><code>java.util.logging</code></a> or any of the many fine third-party logging frameworks around.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload