Java: An exception thrown in the constructor, can my object still be thrown?

Could you say that there may be some case when the constructor throws an exception and the object is not equal to zero. I mean, part of the object is created, and the other is not. Like this

public Test(){ name = "John"; // exception // init some other data. } 

I understand that in this syntax object Test will be null, but there may be a situation where the object test cannot be null (deleting the exception block is not the answer :))?

+7
source share
4 answers

The expression for creating an instance of a class always creates a new object if the evaluation of its qualifier and arguments is performed normally, and if there is enough space to create the object. It doesn't matter if the constructor throws an exception; the object is still being created. In this case, the instantiation expression of the class is not executed normally, but when the exception is thrown.

However, you can still get a link to the new object. Consider the following:

 public class C { static C obj; // stores a "partially constructed" object C() { C.obj = this; throw new RuntimeException(); } public static void main(String[] args) { C obj; try { obj = new C(); } catch (RuntimeException e) { /* ignore */ } System.out.println(C.obj); } } 

Here, the link to the new object is stored elsewhere until an exception is thrown. If you run this program, you will see that the object is really not null, although its constructor did not complete normally.

+19
source

Not. Look at the client code:

 Test myObj = null; try { myObj = new Test(); } catch(MyException e) { System.out.println("" + myObj); } 

Here, when an exception occurs, the operation '=' is not performed. Your code goes straight into the catch block, and myObj remains null .

+4
source

Not. If an exception occurs during object creation, it will not be thrown.

Anyway, would you do it?

 MyObject obj = new MyObject(); // This code will not be reachable in case of an Exception 

or

 MyObject obj = null; try { obj = new MyObject(); } catch (AnyException e) { } // Here, either obj is created correctly, or is null as an Exception occurred. 
+2
source
  public Test() { name = "John"; try{ // exception // init some other data. }catch(AnyException e) { //catch } } 

The above code makes sense according to ur expectation.

-one
source

All Articles