c******n 发帖数: 4965 | 1 /* generate a bunch of "random" numbers
taken in serial one by one from a list of numbers in
a given file
*/
class RandomGen(
public RandomGen() throws IOException {
InputStream ios = ..... open "rand.txt" in CLASSPATH;
//
read the file into memory,
}
int idx;
public Integer gen() {
return list_of_numbers[idx++];
}
}
something like the above.
the problem is that the constructor throws IOException, so if I use this
class, and most likely I use it as a static member var:
class MyClass {
static RandomGen gen = new RandomGen();
....
}
then I can't throw in the static initializer.
what is your strategy of handling this?
1) let ctor of RandomGen throw RuntimeException instead?
2) catch the IOException in static initializer of MyClass?
3) ???
Thanks | g*****g 发帖数: 34805 | 2 What's wrong with a static initialization block?
static {
catch your exception here if you wish
}
【在 c******n 的大作中提到】 : /* generate a bunch of "random" numbers : taken in serial one by one from a list of numbers in : a given file : */ : class RandomGen( : public RandomGen() throws IOException { : InputStream ios = ..... open "rand.txt" in CLASSPATH; : // : read the file into memory, : }
| c******n 发帖数: 4965 | 3 sure I can do that,
it's just that , for example, if this is some error that prevents user from
going further (for example missing the random.txt source in our case), then
it means we'd better halt the code.
doing this catch in initialization block would need me
to do
System.exit(-1) to halt it,
while just percolating the RuntimeException would automatically halt it
without adding too much distraction to the code
【在 g*****g 的大作中提到】 : What's wrong with a static initialization block? : static { : catch your exception here if you wish : }
|
|