JAVA.CTOR.EXCEPT

Be wary of letting constructors throw exceptions

Vulnerability and risk

Constructors that throw exceptions may lead to partially initialised objects that can lead to subsequent unexpected outcomes.

Mitigation and prevention

Limit use of exceptions in constructors or handle correctly.

Vulnerable code example

Copy
package com.klocwork;

import java.io.IOException;

public class JAVA_CTOR_EXCEPT_POSITIVE {
    public JAVA_CTOR_EXCEPT_POSITIVE(boolean check) throws IOException {
        if (check) {
            System.out.println("hello world");
        } else {
            throw new IOException("...");
        }        
    }
}

Fixed code example

Copy
package com.klocwork;

public class JAVA_CTOR_EXCEPT_NEGATIVE {
    public JAVA_CTOR_EXCEPT_NEGATIVE() {
        System.out.println("hello world");
    }
}

External guidance