Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Chapter 7. Error Handling > Bibliography - Pg. 112

112 Chapter 7: Error Handling public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw InvalidArgumentException( "Invalid argument for MetricsCalculator.xProjection"); } return (p2.x ­ p1.x) * 1.5; } } Is this better? It might be a little better than a null pointer exception, but remember, we have to define a handler for InvalidArgumentException . What should the handler do? Is there any good course of action? There is another alternative. We could use a set of assertions: public class MetricsCalculator { public double xProjection(Point p1, Point p2) { assert p1 != null : "p1 should not be null"; assert p2 != null : "p2 should not be null"; return (p2.x ­ p1.x) * 1.5; } } It's good documentation, but it doesn't solve the problem. If someone passes null , we'll still have a runtime error. In most programming languages there is no good way to deal with a null that is