Constructor processing exception and use of this Java keyword

I have two constructors for my class, one of which accepts an object File, and the other accepts an object String, and I want to use the keyword this. A function with an implementation is a parameter Fileas a parameter, and one with Stringwill call this. Now I want to check the exception in the constructor that accepts String, but I get an error that thisshould be the first line. How to check for errors and then call this.

Here is my code:

public Test (String filename) {
    if (filename == null)
        throw new NullPointerException("The String you entered is null.");
    if (filename.isEmpty())
        throw new IllegalArgumentException("The String you entered is empty.");

    this(new File(filename)); // error
}

public Test (File f) {
    /* implementation here */
}

This is the exact error: Constructor call must be the first statement in a constructor

+5
source share
3 answers

, Java . .

Java , factory, . factory , , .

public static Test create(String filename){
    if (filename == null)
        throw new NullPointerException("The String you entered is null.");
    if (filename.isEmpty())
        throw new IllegalArgumentException("The String you entered is empty.");
    return new Test(filename);
}

private Test (String filename) {
    this(new File(filename)); 
}

public Test (File f) {
    /* implementation here */
}

- -, . , - , , , - Java-. , Java, AspectJ.

: , . -, , , -. , , .

public Test (String filename) {
    this(doChecks(filename), new File(filename));
}

private static Void doChecks(String filename){
    if (filename == null)
        throw new NullPointerException("The String you entered is null.");
    if (filename.isEmpty())
        throw new IllegalArgumentException("The String you entered is empty.");
    return null;
}

public Test (Void dummy, File f) {
    this(f);
}

public Test (File f) {
    /* implementation here */
}
+2

, this. . , . new File(filename) .

edit: aizen92: , , , , ?

public Test (String filename) {
    this((filename == null || filename.isEmpty()) ? null : new File(filename)); 
}
0

If we use the constructor thiseither superin the constructor, either this, or supershould be the first statement in the constructor. It is better if you selected an exception from a specific constructor.

public Test (String filename) {
    this(new File(filename));
}

Let the second constructor handle any exception caused by the transfer null.

public Test (File file) {
    // exception handling code
    // or new instance creation
}
0
source

All Articles