Fun Stuff > CLIKC

A programming thread!

<< < (14/37) > >>

snalin:
By the way, the reason for wanting the code to throw an exception is this: if the constructor is a part of a bigger application, and a faulty constructor call simply makes the code return an invalid object, the error (the faulty call) will cause an explosion - but not where it happened. Instead, the faulty object will propagate through the system, and cause seemingly completely unrelated errors somewhere else.

In this case, I can imagine a flaw in the code that constructs the Triangle causing a division-by-zero exception much further on in the program, where some other piece is trying to figure out the angles of the triangle. Or something like that. A very important software engineering principle is this: an exception should be thrown in the first place it is possible that it is thrown, as that will make finding out why it happened easier.

ChaoSera:
Oh, I didn't see that the method in question was a constructor. In that case, yes, throw an exception. In all other cases, returning null is usually the way to handle faulty input. Just always remember to specify that in the javadoc. Because if you'd be working in a larger team and somebody else used the method you wrote, he knows he has to check the outcome for Nullpointers. (It always somewhat bugged me that in Java a "NullPointerException" is thrown in that case, java doesn't have pointers...)

snalin:
Java does have pointers. In fact, it only has pointer. So a nullpointer is correct - you're trying to access a method or variable from a pointer, but that pointer points to null instead of an actual object.

You can see the pointer behavior in code like:


--- Code: --- public static void main(String[] args) {
String s = "This is a pointer to a String";
change(s);
System.out.println(s); //prints "This is a pointer to a String
}

private static void change(String s) {
s = "This makes the local s variable point to a different String";
}

--- End code ---

This is a pretty good article about how things work: Java is Pass-by-Value, Dammit!

ankhtahr:
Seriously, thank you so much, Snalin, I feel like I've learnt more about Java from your help with this exercise sheet than from the lecture itself.

I'm finished with it now, and can now turn to the fun part of the exercise sheets which are due tomorrow. The technical computer science exercise sheet which is mostly C.

The more I do with Java and the more I do with C, the more I dislike the first and the more I like the latter.

Masterpiece:
See, I think that is weird, because I liked Java, adore C# and always watch C with caution.

Why hate on higher programming languages?

Navigation

[0] Message Index

[#] Next page

[*] Previous page

Go to full version