Java: How to pass an exception in the constructor of the singleton class getInstance()?

0 like 0 dislike
4 views
There is code like this (in this case non — working):

public class SingletonClass { public SingletonClass() throws Throwable { /* ... */ } public static SingletonClass getInstance() throws Throwable { return SingletonHolder.instance; } private static class SingletonHolder { public static SingletonClass instance = new SingletonClass(); } }



Ie I need to pass an exception constructor in getInstance(), but because it is initialized statically (tried including and using static { }), I don't ask throws.


I hope it is clear explained :)
by | 4 views

3 Answers

0 like 0 dislike
In this version — no way.
Solutions
1. Use the Spring to a singleton instance (best)
2. Perversion is in the designer make try{}catch{}(). If there is acceptn — save it in another static variable. getInstance() will check if saved acceptn — it will throw out if no — go to field with the instance and return it. Only I wouldn't do :)
3. Initialize the singleton at the beginning of the program. In one place. Then you don't have to write a getInstance() and use a public static field of a class
\r
Seriously — if the singleton's constructor can throw, acceptn — use Spring, Luke
by
0 like 0 dislike
What this code does not fit?
\r
\r
public class ThrowSingleton { static public void main(String args[]) throws Throwable { SingletonClass.getInstance().toString(); } } class SingletonClass { public SingletonClass() throws Throwable { throw new Exception(); } private static SingletonClass instance; public static SingletonClass getInstance() throws Throwable { if (instance != null) { instance = new SingletonClass(); } return SingletonClass.instance; } } 

\r
I do not quite understand why make a private subclass which keeps a singleton.
by
0 like 0 dislike
The first two options here for you.
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
4 answers
0 like 0 dislike
7 answers
0 like 0 dislike
7 answers
asked Mar 24, 2019 by azverin
110,608 questions
257,186 answers
0 comments
28,803 users