Redian新闻
>
what is your opinion in this case?
avatar
what is your opinion in this case?# Java - 爪哇娇娃
c*n
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
avatar
g*g
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,
: }

avatar
c*n
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
: }

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。