Supuhstar Supuhstar - 4 months ago 7x
Java Question

How can I create a static final

My question is simple. I'm trying to make a set of
s that are
public static final
, so that any class can access them from any context, as these URLs won't change during runtime. However, when I try to create them, I get a compiler error telling me that I must catch or declare thrown a
, but that is impossible outside a method. Is there any way to circumvent such a constructor that throws a non-

Some dummy code below to visualize my problem:

public class Main
public static final STATIC_URL = new"");
public static void main(String[] args)
GUI gui = new GUI();

public class GUI extends java.awt.Window
public GUI()
add(new java.awt.Label(Main.STATIC_URL.toString()));

If you try to compile this, it will tell you that you can't because of line 3. Hence my question.


Use a static initializer:

public class Main {
    private static final STATIC_URL;
    static { temp;
        try {
            temp = new"");
        } catch ( e) {
            temp = null;
        STATIC_URL = temp;

Note: The usage of a temporary variable is required to avoid a compilation error about assigning to the final static field twice. If the field is not final, the assignment could be done directly.