• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

.

KingNothing

Diamond Member
I'm using Sun Java 1.4, and the idea here is to make the SpellChecker class so only one instance is around at any given time. I can't figure out how to create the instance the first time around though because it gives me this error:

Edit: Thanks for the tips on exceptions, this was actually a problem in the exception my constructor was throwing for file access.

===================================
public class SpellChecker
{
private static SpellChecker instance;
private static int numInstances = 0;

private SpellChecker() throws Exception
{
//code to read in words
}

public static SpellChecker getInstance()
{
try
{
if (numInstances == 0)
{
instance = new SpellChecker();
numInstances++;
}
}
catch (Exception e)
{
e.printStackTrace();
}

return instance;
}
==========================
import java.io.*;
import java.util.*;

public class test
{
public static void main(String arg[])
{
try
{
SpellChecker s = SpellChecker.getInstance();
if (null == s)
System.out.println("Cannot get spellchecker");

}
catch (Exception e)
{
e.printStackTrace();
}
}
}
 
If you're going to throw an exception: private SpellChecker() throws Exception
then you've got to catch that exception when you run that function.
 
The problem is that your private constructor throws an Exception that must be caught somewhere. There are two places to catch it and deal with it. The first is in the getInstance method:

try {
instance = new SpellChecker(
} catch (Exception e) {
// Do something cool here.
}

or you can catch it in the main method of the test class that calls the getInstance method. If you do this, then you will need to change the getInstance declaration to also throw the Exception:

public static SpellChecker getInstance() throws Exception

AND

try {
SpellChecker s = SpellChecker.getInstance();
} catch (Exception e) {
// Do something cool here.
}

 
You can use a try-catch block inside a static code block that initializes the singleton instance.

But a constructor that throws an exception is usually bad form. A constructor should do minimal work to bring an instance into existence, for example setting member fields to initial values. Usually you would factor out more complex logic, such as anything that would throws exceptions, into member function(s).
 
Back
Top