NullPointerException using jsf [duplicate] - jsf
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
There are two overarching types of variables in Java:
Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.
References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.
Consider the following code where you declare a variable of primitive type int and don't initialize it:
int x;
int y = x + x;
These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.
Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).
If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.
The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.
Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.
In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.
If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:
doSomething(null);
In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.
If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.
In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:
// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:
/**
* #param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
What methods/tools can be used to determine the cause so that you stop
the exception from causing the program to terminate prematurely?
Sonar with find bugs can detect NPE.
Can sonar catch null pointer exceptions caused by JVM Dynamically
Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.
In Java 14, the following is a sample NullPointerException Exception message:
in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
List of situations that cause a NullPointerException to occur
Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:
Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
Calling an instance method of a null reference. (static methods don't count!)
throw null;
Accessing elements of a null array.
Synchronising on null - synchronized (someNullReference) { ... }
Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
An unboxing conversion throws a NullPointerException if the boxed value is null.
Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
class Inner {}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner(Outer o) {
o.super(); // if o is null, NPE gets thrown
}
}
Using a for (element : iterable) loop to loop through a null collection/array.
switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.
foo.new SomeInnerClass() throws a NullPointerException when foo is null.
Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.
a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!
* Note that the JLS probably also says a lot about NPEs indirectly.
NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException would be:
public class Example {
public static void main(String[] args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
Otherwise, if the value of the Expression is null, a NullPointerException is thrown.
How do I fix it?
So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null.
Trace where these values should be set
Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName() before calling printer.print().
Other fixes
The variable can have a default value (and setName can prevent it being set to null):
private String name = "";
Either the print or printString method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
Question: What causes a NullPointerException (NPE)?
As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".
A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String[] args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.
There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:
assign it to a reference variable or read it from a reference variable,
assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
pass it as a parameter or return it as a result, or
test it using the == or != operators, or instanceof.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
"at Test.main" says that we were in the main method of the Test class.
"Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
See also: What is a stack trace, and how can I use it to debug my application errors?
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG!
But (I hear you say) what if the NPE was thrown inside the length() method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line.
So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String[] foo = new String[2];
private static int test(String[] bar, int pos) {
return bar[pos].length();
}
public static void main(String[] args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
If the value of bar is null then bar[pos] will throw an NPE.
If the value of bar[pos] is null then calling length() on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)
So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String[] foo = new String[2];
we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.
What about on Android?
On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.
But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.
It's like you are trying to access an object which is null. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.
In general, it's because something hasn't been initialized properly.
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerExceptions at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final modifier.
Using the "final" modifier whenever applicable in Java
Summary:
Use the final modifier to enforce good initialization.
Avoid returning null in methods, for example returning empty collections when applicable.
Use annotations #NotNull and #Nullable
Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
Use equals with a known object first: if("knownObject".equals(unknownObject)
Prefer valueOf() over toString().
Use null safe StringUtils methods StringUtils.isEmpty(null).
Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student student;
public School() {
try {
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
Because you are using student, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student student;
public School() {
try {
student = new Student();
student.setId(12);
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
In Java, everything (excluding primitive types) is in the form of a class.
If you want to use any object then you have two phases:
Declare
Initialization
Example:
Declaration: Object object;
Initialization: object = new Object();
Same for the array concept:
Declaration: Item item[] = new Item[5];
Initialization: item[0] = new Item();
If you are not giving the initialization section then the NullPointerException arise.
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.
You must initialize the elements in the array before accessing or dereferencing them.
String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
Related
Liferay instance setting [duplicate]
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions. What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
There are two overarching types of variables in Java: Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references. Consider the following code where you declare a variable of primitive type int and don't initialize it: int x; int y = x + x; These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated. Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null). If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException. The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist. Take the following code: Integer num; num = new Integer(10); The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null. In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object. If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object. For instance, you may have a method as follows: public void doSomething(SomeObject obj) { // Do something to obj, assumes obj is not null obj.myMethod(); } In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this: doSomething(null); In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException. If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes. In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method: // Throws an NPE with a custom error message if obj is null Objects.requireNonNull(obj, "obj must not be null"); Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely. Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as: /** * #param obj An optional foo for ____. May be null, in which case * the result will be ____. */ public void doSomething(SomeObject obj) { if(obj == null) { // Do something } else { // Do something else } } Finally, How to pinpoint the exception & cause using Stack Trace What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely? Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. In Java 14, the following is a sample NullPointerException Exception message: in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null List of situations that cause a NullPointerException to occur Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification: Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!) Calling an instance method of a null reference. (static methods don't count!) throw null; Accessing elements of a null array. Synchronising on null - synchronized (someNullReference) { ... } Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference An unboxing conversion throws a NullPointerException if the boxed value is null. Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations: class Outer { class Inner {} } class ChildOfInner extends Outer.Inner { ChildOfInner(Outer o) { o.super(); // if o is null, NPE gets thrown } } Using a for (element : iterable) loop to loop through a null collection/array. switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null. foo.new SomeInnerClass() throws a NullPointerException when foo is null. Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null. a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE! * Note that the JLS probably also says a lot about NPEs indirectly.
NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page. Probably the quickest example code I could come up with to illustrate a NullPointerException would be: public class Example { public static void main(String[] args) { Object obj = null; obj.hashCode(); } } On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing. (This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
What is a NullPointerException? A good place to start is the JavaDocs. They have this covered: Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value. Applications should throw instances of this class to indicate other illegal uses of the null object. It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS: SynchronizedStatement: synchronized ( Expression ) Block Otherwise, if the value of the Expression is null, a NullPointerException is thrown. How do I fix it? So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException: public class Printer { private String name; public void setName(String name) { this.name = name; } public void print() { printString(name); } private void printString(String s) { System.out.println(s + " (" + s.length() + ")"); } public static void main(String[] args) { Printer printer = new Printer(); printer.print(); } } Identify the null values The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown: Exception in thread "main" java.lang.NullPointerException at Printer.printString(Printer.java:13) at Printer.print(Printer.java:9) at Printer.main(Printer.java:19) Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method. Trace where these values come from Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null. Trace where these values should be set Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method. This is enough to give us a solution: add a call to printer.setName() before calling printer.print(). Other fixes The variable can have a default value (and setName can prevent it being set to null): private String name = ""; Either the print or printString method can check for null, for example: printString((name == null) ? "" : name); Or you can design the class so that name always has a non-null value: public class Printer { private final String name; public Printer(String name) { this.name = Objects.requireNonNull(name); } public void print() { printString(name); } private void printString(String s) { System.out.println(s + " (" + s.length() + ")"); } public static void main(String[] args) { Printer printer = new Printer("123"); printer.print(); } } See also: Avoiding “!= null” statements in Java? I still can't find the problem If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
Question: What causes a NullPointerException (NPE)? As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object". A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this: public class Test { public static void main(String[] args) { String foo = null; int length = foo.length(); // HERE } } the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException. There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are: assign it to a reference variable or read it from a reference variable, assign it to an array element or read it from an array element (provided that array reference itself is non-null!), pass it as a parameter or return it as a result, or test it using the == or != operators, or instanceof. Question: How do I read the NPE stacktrace? Suppose that I compile and run the program above: $ javac Test.java $ java Test Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:4) $ First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.) Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully. So let's look at what it says: Exception in thread "main" java.lang.NullPointerException The first line of the stack trace tells you a number of things: It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ... It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException. If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message. The second line is the most important one in diagnosing an NPE. at Test.main(Test.java:4) This tells us a number of things: "at Test.main" says that we were in the main method of the Test class. "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file. If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment. Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1. In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE. See also: What is a stack trace, and how can I use it to debug my application errors? 1 - Not quite true. There are things called nested exceptions... Question: How do I track down the cause of the NPE exception in my code? This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation. Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened: int length = foo.length(); // HERE How can that throw an NPE? In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG! But (I hear you say) what if the NPE was thrown inside the length() method call? Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line. So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.) OK, so let's try a slightly more tricky example. This will require some logical deduction. public class Test { private static String[] foo = new String[2]; private static int test(String[] bar, int pos) { return bar[pos].length(); } public static void main(String[] args) { int length = test(foo, 1); } } $ javac Test.java $ java Test Exception in thread "main" java.lang.NullPointerException at Test.test(Test.java:6) at Test.main(Test.java:10) $ So now we have two "at" lines. The first one is for this line: return args[pos].length(); and the second one is for this line: int length = test(foo, 1); Looking at the first line, how could that throw an NPE? There are two ways: If the value of bar is null then bar[pos] will throw an NPE. If the value of bar[pos] is null then calling length() on it will throw an NPE. Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one: Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.) So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible? Indeed it is! And that is the problem. When we initialize like this: private static String[] foo = new String[2]; we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null. What about on Android? On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause. But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.
It's like you are trying to access an object which is null. Consider below example: TypeA objA; At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense. See this below example as well: String a = null; System.out.println(a.toString()); // NullPointerException will be thrown
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value. Applications should throw instances of this class to indicate other illegal uses of the null object. Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception. In general, it's because something hasn't been initialized properly.
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerExceptions at all. See also: A good list of best practices I would add, very important, make a good use of the final modifier. Using the "final" modifier whenever applicable in Java Summary: Use the final modifier to enforce good initialization. Avoid returning null in methods, for example returning empty collections when applicable. Use annotations #NotNull and #Nullable Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null. Use equals with a known object first: if("knownObject".equals(unknownObject) Prefer valueOf() over toString(). Use null safe StringUtils methods StringUtils.isEmpty(null). Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.
A null pointer exception is an indicator that you are using an object without initializing it. For example, below is a student class which will use it in our code. public class Student { private int id; public int getId() { return this.id; } public setId(int newId) { this.id = newId; } } The below code gives you a null pointer exception. public class School { Student student; public School() { try { student.getId(); } catch(Exception e) { System.out.println("Null pointer exception"); } } } Because you are using student, but you forgot to initialize it like in the correct code shown below: public class School { Student student; public School() { try { student = new Student(); student.setId(12); student.getId(); } catch(Exception e) { System.out.println("Null pointer exception"); } } }
In Java, everything (excluding primitive types) is in the form of a class. If you want to use any object then you have two phases: Declare Initialization Example: Declaration: Object object; Initialization: object = new Object(); Same for the array concept: Declaration: Item item[] = new Item[5]; Initialization: item[0] = new Item(); If you are not giving the initialization section then the NullPointerException arise.
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves. When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException. Your reference is "pointing" to null, thus "Null -> Pointer". The object lives in the VM memory space and the only way to access it is using this references. Take this example: public class Some { private int id; public int getId(){ return this.id; } public setId( int newId ) { this.id = newId; } } And on another place in your code: Some reference = new Some(); // Point to a new object of type Some() Some otherReference = null; // Initiallly this points to NULL reference.setId( 1 ); // Execute setId method, now private var id is 1 System.out.println( reference.getId() ); // Prints 1 to the console otherReference = reference // Now they both point to the only object. reference = null; // "reference" now point to null. // But "otherReference" still point to the "real" object so this print 1 too... System.out.println( otherReference.getId() ); // Guess what will happen System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember... This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it. String[] phrases = new String[10]; String keyPhrase = "Bird"; for(String phrase : phrases) { System.out.println(phrase.equals(keyPhrase)); } This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object. All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null. You must initialize the elements in the array before accessing or dereferencing them. String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"}; String keyPhrase = "Bird"; for(String phrase : phrases) { System.out.println(phrase.equals(keyPhrase)); }
The JUnit Assume.assumeNotNull throws nullpointer instead of skipping test
I have this junit (using JUnit 4.12) test in groovy that should only be executed if getenv != null: import org.junit.Assume import org.junit.Before import org.junit.Ignore import org.junit.Test ... #Test public void skipWhenNull() throws Exception { def getenv = System.getenv("bogos") if( getenv == null) { println "Its null!" } Assume.assumeNotNull(getenv); println "Test executing!" } But when I run the test it prints: Its null! and then throws a NullPointer exception (in the line: Assume.assumeNotNull(getenv); ). Is the point of: Assume.assumeNotNull(expr) not that it will skip the test when expr evaluates to null instead of throwing a Nullpointer?
I thought this might be a bug, but I think this is rather a consequence of Groovy's dynamic type system in its default behavior. Assume.assumeNotNull(Object... objects) method uses varargs parameters. It means that in case of passing a non-array element compiler wraps it within an array of expected type. String getenv = System.getenv("bogos"); Assume.assumeNotNull(getenv); // --> Assume.assumeNotNull(new Object[] { getenv }); This is what Java's static compiler does. So in case of getenv == null we end up with: Assume.assumeNotNull(new Object[] { null }); A non-empty array that contains a single null element. On the other hand, if we specify a variable with an array type and we assign a null value to it, calling the same method will cause NullPointerException, just like in the following example: String[] array = null; Assume.assumeNotNull(array); // --> throws NPE This is at least what happens in Java. Now, why it fails in Groovy unit test? Groovy is a dynamically typed language by default, so it behaves quite differently in this area. It seems like Groovy's type system applies null value to the method type without wrapping it within an array, so in case of passing a null to a method that expects e.g. Object... objects we always get objects == null instead of objects == new Object[] { null }. I started questioning myself if this is a bug or not. From one perspective I would expect dynamic Groovy to behave in the same way that statically compiled code behaves. But on the other hand in a dynamically typed system, this distinction is acceptable (and maybe even desirable), because dynamic type system infers the type at the runtime. It sees null so it thinks that we intend to assign null value to a variable of type Object[]. Solution There are two ways you can solve this problem. 1. Enable static compilation If you don't use Groovy's dynamic and metaprogramming features in your test case you can easily annotate it with #groovy.transform.CompileStatic annotation to generate a bytecode that is more similar to Java's bytecode. For instance, this is what the bytecode of your method in the dynamic Groovy looks like: #Test public void skipWhenNull() throws Exception { CallSite[] var1 = $getCallSiteArray(); Object getenv = var1[4].call(System.class, "bogos"); if (ScriptBytecodeAdapter.compareEqual(getenv, (Object)null)) { var1[5].callCurrent(this, "Its null!"); } var1[6].call(Assume.class, getenv); var1[7].callCurrent(this, "Test executing!"); } And here is the same method but annotated with #CompileStatic from the bytecode perspective: #Test public void skipWhenNull() throws Exception { String getenv = System.getenv("bogos"); Object var10000; if (getenv == null) { DefaultGroovyMethods.println(this, "Its null!"); var10000 = null; } Assume.assumeNotNull(new Object[]{getenv}); var10000 = null; DefaultGroovyMethods.println(this, "Test executing!"); var10000 = null; } 2. Wrap getenv with an array Alternatively, you can make more explicit call to Assume.assumeNotNull method. If you replace: Assume.assumeNotNull(getenv); with: Assume.assumeNotNull([getenv] as Object[]); then you will wrap parameter explicitly with Object[] array and you will prevent from passing an array object that is represented by null, but a single element array holding null value instead.
Achilles Cassandra - Getting result of conditional update
How to get response when performing a conditional update/delete from Achilles? I tried using a custom ResultListener, but it doesn't always work correctly. public class ResultListener implements LWTResultListener { private boolean applied; #Override public void onSuccess() { applied = true; } #Override public void onError(LWTResult lwtResult) { applied = false; } public boolean isApplied() { return applied; } } From my caller class, I call isApplied() but it seems that the onSuccess method is called asynchronously. The caller class doesn't see the updated value of applied field.
That's not the problem with Cassandra/Achilles itself, but general problem with async programming - callback could be called at any point of time... For your code there are 2 things: First, you need to understand if the callback was called or not - you may add another boolean variable that will be set by both onSuccess & onError to indicate that callback was called already. And your code need to check this variable before calling isApplied; Second - you need to guarantee that the change is visible by other parts of the code. You can add the volatile keyword to the declaration of applied variable (and to the declaration of variable described above). This keyword will indicate that data could be changed by some other thread, and Java will enforce that data is always read from memory. Following article describes this in quite good details.
Is there a way to prevent Geb from returning null from void methods?
In a Spock Specification any line in expect: or then: block is evaluated and asserted as boolean, unless it has signature with return type void. I've noticed that there is something odd going on for methods declared as void on any class inheriting from Navigator (for example Page or Module classes). Let say we have such example: class NavigationSpec extends GebSpec { def 'Collections page has a right header'() { when: to CollectionsPage then: hasHeaderText('Collections') } } The hasHeaderText() method is defined within CollectionsPage class as follows: class CollectionsPage extends Page { static url = 'movies/collections' void hasHeaderText(String expectedText) { assert true } } On purpose I'm just asserting true over there so it should never fail. Even though it fails with an error: Condition not satisfied: hasHeaderText('Collections') | null How and why a void method call result is evaluated as null? I know how to 'fix it'. It's enough to declare the method return type as boolean and return true. This is ugly though as following all the asserts otherwise unnecessary return true has to be added like: boolean hasHeaderText(String expectedText) { assert header.text() == expectedText return true } This causes only noise though. Is there any way to prevent Geb from returning null from void methods? I'm, of course, aware that this specific case could go like: boolean hasHeaderText(String expectedText) { header.text() == expectedText` } This doesn't explain the oddity of lost void return type, not to mention we loose meaningful assert failure message with such approach.
It's part of the Groovy language that every method returns a value. This allows any method to be used in expressions or as lambdas. All methods that are declared void return null. If you don't explicitly have any return statement, the result of the last expression in your method is returned. You can look at the bytecode... even if you declare a return type, you don't actually need to return anything as Groovy will, by default, return null: // returns null String callMe() { } static void main(args) { def x = callMe() assert x == null println "OK!" } Because Spock will assert anything in the then block which is not a simple assignment, you need to avoid doing anything other than boolean assertions in the then block. Even assigning a variable, though allowed, should be avoided... It's hard to keep tests clean and clear, and by adhering to these guidelines will really work for you in the long run, not against you. So, the correct way to write the assertion you want is to make your method return a boolean: boolean hasHeaderText(String expectedText) { header.text() == expectedText } And use it in the then block: then: 'The header has the expected text #expectedText' hasHeaderText expectedText Looks pretty good if you ask me. EDIT I've noticed that Groovy/Spock actually will not assert the result of a normal void method even in the then block... What's probably going on here is that you don't have a normal void method, you seem to be calling a dynamic method of CollectionsPage (I guess that's Geb's magic in play), which means that, probably, the Spock AST Transformer does not have the opportunity to check the signature of the method you're calling, so it correctly assumes it must assert the result... at least that's what it looks like.
#Renato is correct in the edited part of his response - your call to a void method gets asserted by Spock because it's a dynamic call and Spock isn't able to figure out that you are calling a void method and eagerly asserts the call. If you changed your code to: class NavigationSpec extends GebSpec { def 'Collections page has a right header'() { when: CollectionsPage collectionsPage = to CollectionsPage then: collectionsPage.hasHeaderText('Collections') } } then it won't get asserted.
Throw specific exception for a violation of a contract on an automatic property
I can specify a contract for an automatic property like this (example taken from the CC documentation): public int MyProperty { get; set ; } [ContractInvariantMethod] private void ObjectInvariant () { Contract. Invariant ( this .MyProperty >= 0 ); ... } When runtime-checking is turned on, and an attempt is made to assign an invalid value to MyProperty, the setter throws System.Diagnostics.Contracts.__ContractsRuntime+ContractException. Is there a way to make it throw a specific type of exception - typically, ArgumentNullException, ArgumentOutOfRangeException, or similar, without having to go back and implement the property manually using a backing field and Requires<> ?
No, there isn't. But as long as your property setter is private, you don't have to worry about that. Any ArgumentException that would be thrown from your setter indicates a bug in the code calling that setter, and should be fixed there. The only code that can call your setter is your own. If your property setter is protected or public, then you do need to specify which ArgumentException gets thrown for which values.
From the Code Contracts manual: Object invariants are conditions that should hold true on each instance of a class whenever that object is visible to a client. They express conditions under which the object is in a "good" state. There's a peculiar couple of sentences in the manual at the top of page 10: Invariants are conditionally defined on the full-contract symbol [CONTRACT_FULL]. During runtime checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, then the invariant check that would normally happen at the end of that public method is disabled and checked only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class. — text in brackets is mine; this is the compile time symbol the manual is referencing which is defined. Since properties are really just syntactic sugar for T get_MyPropertyName() and void set_MyPropertyName(T), these sentences would seem to apply to properties, too. Looking in the manual, when they show an example of defining object invariants, thy show using private fields in the invariant contract conditions. Also, invariants don't really communicate to consumers of your library what the pre-conditions or post-conditions for any particular property or method are. Invariants, again, only state to consumers of the library what conditions "hold true on each instance of a class whenever that object is visible to a client." That's all they do. In order to state that if an invalid value will result in throwing an exception, you must specify a pre-condition, which is demonstrated below. Therefore, it would appear that in order to best achieve what you're looking for, it's as hvd says: it's best to have a private backing field and place the invariant on the backing field. Then you would also provide the contracts on the property getter/setter so that consumers of your library know what the pre-conditions and guaranteed post-conditions (if any) are. int _myPropertyField = 0; [ContractInvariantMethod] private void ObjectInvariants() { Contract.Invariant(_myPropertyField >= 0); } public int MyProperty { get { Contract.Ensures(Contract.Result<int>() >= 0); return _myPropertyField; } set { Contract.Requires<ArgumentOutOfRangeException>(value >= 0); _myPropertyField = value; } } Now, there is another way to throw a specific exception using "legacy" code contracts (e.g. if-then-throw contracts). You would use this method if you're trying to retrofit contracts into an existing codebase that was originally written without contracts. Here's how you can do this without using Contract.Requires<TException>(bool cond): Basically, in Section 5: Usage Guidelines of the manual, you'll be referencing Usage Scenario 3, legacy contract checking (see page 20). This means you need to set the following options in the Code Contracts project properties dialog: Ensure that the Assembly Mode is set to Custom Parameter Validation. Use "if-then-throw" guard blocks and perform manual inheritance.private Ensure Contract.EndContractBlock() follows these guard blocks. Check Perform Runtime Contract Checking and select the level of checking you want, but only on Debug builds—not on Release builds. Feel free to use Contract.Requires(bool cond) (non-generic form) on private API methods (e.g. methods not directly callable by a library consumer). Then, you could write the following code: private int _myPropertyField = 0; [ContractInvariantMethod] private void ObjectInvariants() { Contract.Invariant(_myPropertyField >= 0); } public int MyProperty { get { Contract.Ensures(Contract.Result<int>() >= 0); return _myPropertyField; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } Contract.EndContractBlock(); _myPropertyField = value; } } Now, you specifically stated that you didn't want to have to go back and create private backing fields for all of your properties. Unfortunately, if this is a public property than can be mutated, then there really is no way to good avoid this. One possible way to avoid this, though, is to make your setter private: public int MyProperty { get; private set; } [ContractInvariantMethod] private void ObjectInvariants() { Contract.Invariant(MyProperty >= 0); } public SetMyProperty(int value) { // Using Code Contracts with Release and Debug contract checking semantics: Contract.Requires<ArgumentOutOfRangeException>(value >= 0); // Or, using Code Contracts with Debug-only contract checking semantics: Contract.Requires(value >= 0); // Using Legacy contracts for release contract checking without throwing // a ContractException, but still throwing a ContractException for // debug builds if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } Contract.EndContractBlock(); MyProperty = value; } However, I must admit, I'm not really sure what you're gaining at this point by implementing invariants in this manner. You might as well just bite the bullet and use one of the first two examples I demonstrated above. Addendum, 2016-02-22 The OP notes in their comment that Section 2.3.1 of the manual mentions that defining object invariants on auto-properties results in the invariant essentially becoming a precondition on the setter and a postcondition on the getter. That's correct. However, the preconditions that are created use the non-generic Contract.Requires(bool condition) form. Why? So that when invariants are used by those who don't want runtime contract checking turned on for their Release builds, they can still use invariants. Therefore, even if you use invariants on properties, if you want a specific exception thrown on contract violations, you must use full properties with backing fields and the generic form of Requires, which also implies that you want to perform runtime contract checking on all builds, including Release builds.