<p>So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor.  What I want to know is, why can't I put a try block around that?</p>

<p>My specific case is that I have a mock class for a test.  There is no default constructor, but I want one to make the tests simpler to read.  I also want to wrap the exceptions thrown from the constructor into a RuntimeException.</p>

<p>So, what I want to do is effectively this:</p>

<pre><code>public class MyClassMock extends MyClass {
    public MyClassMock() {
        try {
            super(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Mocked methods
}
</code></pre>

<p>But Java complains that super isn't the first statement.</p>

<p>My workaround:</p>

<pre><code>public class MyClassMock extends MyClass {
    public static MyClassMock construct() {
        try {
            return new MyClassMock();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public MyClassMock() throws Exception {
        super(0);
    }

    // Mocked methods
}
</code></pre>

<p>Is this the best workaround?  Why doesn't Java let me do the former?</p>

<hr>

<p>My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that.  It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways.</p>

<p>I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.</p>

[{'answer_id': 5351, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 5, 'selected': True, 'text': "<p>Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases.</p>\n\n<p>In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do <em>unsafe</em> things if one knows how to deal with them.</p>\n\n<p>In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this:</p>\n\n<pre><code>public ClassName(...) : base(...)\n</code></pre>\n\n<p>in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.</p>\n"}, {'answer_id': 5357, 'author': 'Telcontar', 'author_id': 518, 'author_profile': 'https://Stackoverflow.com/users/518', 'pm_score': 1, 'selected': False, 'text': "<p>I don't know how Java is implemented internally, but if the constructor of the superclass throws an exception, then there isn't a instance of the class you extend.  It would be impossible to call the <code>toString()</code> or <code>equals()</code> methods, for example, since they are inherited in most cases.</p>\n\n<p>Java may allow a try/catch around the super() call in the constructor if 1. you override ALL methods from the superclasses, and 2. you don't use the super.XXX() clause, but that all sounds too complicated to me.</p>\n"}, {'answer_id': 5360, 'author': 'Ishmaeel', 'author_id': 227, 'author_profile': 'https://Stackoverflow.com/users/227', 'pm_score': 1, 'selected': False, 'text': "<p>I can't presume to have a deep understanding of Java internals, but it is my understanding that, when a compiler needs to instantiate a derived class, it has to first create the base (and its base before that(...)) and then slap on the extensions made in the subclass. </p>\n\n<p>So it is not even the danger of uninited variables or anything like that at all. When you try to do something in the subclass' constructor <em>before</em> the base class' <strong>constructor</strong>, you are basically asking the compiler to extend a base object instance that doesn't exist yet.</p>\n\n<p>Edit:In your case, <strong>MyClass</strong> becomes the base object, and <strong>MyClassMock</strong> is a subclass.</p>\n"}, {'answer_id': 76957, 'author': 'Joshua', 'author_id': 14768, 'author_profile': 'https://Stackoverflow.com/users/14768', 'pm_score': 3, 'selected': False, 'text': "<p>It's done to prevent someone from creating a new <code>SecurityManager</code> object from untrusted code.</p>\n\n<pre><code>public class Evil : SecurityManager {\n  Evil()\n  {\n      try {\n         super();\n      } catch { Throwable t }\n      {\n      }\n   }\n}\n</code></pre>\n"}, {'answer_id': 10261194, 'author': 'Edwin Dalorzo', 'author_id': 697630, 'author_profile': 'https://Stackoverflow.com/users/697630', 'pm_score': 3, 'selected': False, 'text': '<p>I know this is an old question, but I liked it, and as such, I decided to give it an answer of my own. Perhaps my understanding of why this cannot be done will contribute to the discussion and to future readers of your interesting question.</p>\n\n<p>Let me start with an example of failing object construction.</p>\n\n<p>Let\'s define a class A, such that:</p>\n\n<pre><code>class A {\n   private String a = "A";\n\n   public A() throws Exception {\n        throw new Exception();\n   }\n}\n</code></pre>\n\n<p>Now, let\'s assume we would like to create an object of type A in a <code>try...catch</code> block.</p>\n\n<pre><code>A a = null;\ntry{\n  a = new A();\n}catch(Exception e) {\n  //...\n}\nSystem.out.println(a);\n</code></pre>\n\n<p>Evidently, the output of this code will be: <code>null</code>.</p>\n\n<p>Why Java does not return a partially constructed version of <code>A</code>? After all, by the point the constructor fails, the object\'s <code>name</code> field has already been initialized, right?</p>\n\n<p>Well, Java can\'t return a partially constructed version of <code>A</code> because the object was not successfully built. The object is in a inconsistent state, and it is therefore discarded by Java. Your variable A is not even initialized, it is kept as null. </p>\n\n<p>Now, as you know, to fully build a new object, all its super classes must be initialized first. If one of the super classes failed to execute, what would be the final state of the object? It is impossible to determine that.</p>\n\n<p>Look at this more elaborate example</p>\n\n<pre><code>class A {\n   private final int a;\n   public A() throws Exception { \n      a = 10;\n   }\n}\n\nclass B extends A {\n   private final int b;\n   public B() throws Exception {\n       methodThatThrowsException(); \n       b = 20;\n   }\n}\n\nclass C extends B {\n   public C() throws Exception { super(); }\n}\n</code></pre>\n\n<p>When the constructor of <code>C</code> is invoked, if an exception occurs while initializing <code>B</code>, what would be the value of the final <code>int</code> variable <code>b</code>?</p>\n\n<p>As such, the object C cannot be created, it is bogus, it is trash, it is not fully initialized.</p>\n\n<p>For me, this explains why your code is illegal.</p>\n'}, {'answer_id': 22721701, 'author': 'aliteralmind', 'author_id': 2736496, 'author_profile': 'https://Stackoverflow.com/users/2736496', 'pm_score': -1, 'selected': False, 'text': '<p>One way to get around it is by calling a private static function. The try-catch can then be placed in the function body.</p>\n\n<pre><code>public class Test  {\n  public Test()  {\n     this(Test.getObjectThatMightThrowException());\n  }\n  public Test(Object o)  {\n     //...\n  }\n  private static final Object getObjectThatMightThrowException()  {\n     try  {\n        return  new ObjectThatMightThrowAnException();\n     }  catch(RuntimeException rtx)  {\n        throw  new RuntimeException("It threw an exception!!!", rtx);\n     }\n  }\n}\n</code></pre>\n'}, {'answer_id': 43454831, 'author': 'Kröw', 'author_id': 5921170, 'author_profile': 'https://Stackoverflow.com/users/5921170', 'pm_score': 0, 'selected': False, 'text': "<p>I know this question has numerous answers, but I'd like to give my little tidbit on why this wouldn't be allowed, specifically to answer why Java does not allow you to do this. So here you go...</p>\n\n<p>Now, keep in mind that <code>super()</code> has to be called before anything else in a subclass's constructor, so, if you did use <code>try</code> and <code>catch</code> blocks around your <code>super()</code> call, the blocks would have to look like this:</p>\n\n<pre><code>try {\n   super();\n   ...\n} catch (Exception e) {\n   super(); //This line will throw the same error...\n   ...\n}\n</code></pre>\n\n<p>If <code>super()</code> fails in the <code>try</code> block, it HAS to be executed first in the <code>catch</code> block, so that <code>super</code> runs before anything in your subclass`s constructor. This leaves you with the same problem you had at the beginning: if an exception is thrown, it isn't caught. (In this case it just gets thrown again in the catch block.)</p>\n\n<p>Now, the above code is in no way allowed by Java either. This code may execute half of the first super call, and then call it again, which could cause some problems with some super classes.</p>\n\n<p>Now, the reason that Java doesn't let you throw an exception <em>instead</em> of calling <code>super()</code> is because the exception could be caught somewhere else, and the program would continue <strong>without calling <code>super()</code> on your subclass object,</strong> and possibly because the exception could take your object as a parameter and try to change the value of inherited instance variables, which would not yet have been initialized.</p>\n"}]
['https://Stackoverflow.com/questions/5328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122/']