code_junkie

How much null checking is enough?

Nov 12th, 2011
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. try {
  2. MyObject* obj = new MyObject();
  3. if(obj!=NULL) {
  4. //do something
  5. } else {
  6. //??? most code I see has log-it and move on
  7. //or it repeats what's in the exception handler
  8. }
  9. } catch(std::bad_alloc) {
  10. //Do something? normally--this code is wrong as it allocates
  11. //more memory and will likely fail, such as writing to a log file.
  12. }
  13.  
  14. //X is non-negative.
  15. //Returns an object or throws exception.
  16. MyObject* create(int x) {
  17. if(x<0) throw;
  18. return new MyObject();
  19. }
  20.  
  21. try {
  22. MyObject* x = create(unknownVar);
  23. if(x!=null) {
  24. //is this null check really necessary?
  25. }
  26. } catch {
  27. //do something
  28. }
  29.  
  30. //Internal use only--non-public, not part of public API
  31. //input must be non-null.
  32. //returns non-negative value, or -1 if failed
  33. int ParseType(String input) {
  34. if(input==null) return -1;
  35. //do something magic
  36. return value;
  37. }
  38.  
  39. //Internal use only--non-public, not part of public API
  40. //input must be non-null.
  41. //returns non-negative value
  42. int ParseType(String input) {
  43. assert(input!=null : "Input must be non-null.");
  44. //do something magic
  45. return value;
  46. }
  47.  
  48. template<typename T>
  49. static inline void nullcheck(T *ptr) {
  50. #if PLATFORM_TRAITS_NEW_RETURNS_NULL
  51. if (ptr == NULL) throw std::bad_alloc();
  52. #endif
  53. }
  54.  
  55. internal void DoThis(Something thing)
  56. {
  57. Debug.Assert(thing != null, "Arg [thing] cannot be null.");
  58. //...
  59. }
  60.  
  61. public void DoThis(Something thing)
  62. {
  63. if (thing == null)
  64. {
  65. throw new ArgumentException("Arg [thing] cannot be null.");
  66. }
  67. //...
  68. }
  69.  
  70. if(obj==NULL)
  71. throw std::bad_alloc();
  72.  
  73. public MyObject MyMethod(object foo)
  74. {
  75. if (foo == null)
  76. {
  77. throw new ArgumentNullException("foo");
  78. }
  79.  
  80. // do whatever if foo was non-null
  81. }
Add Comment
Please, Sign In to add comment