0

I need some advice on how to deal with null objects being returned and crashing my program. Here is my code:

var employee = _repo.GetEmployeeById(Id); //gets employee by id in ssms
if (employee != null)
{
  //do something if an employee exists
  return employee;
}

return null; //else return nothing

and then:

try
{
  model = await employeeService.GetEmployeeById(Id);
}
catch(NullReferenceException ex)
        {
           //Do something about it...
        }

when an ID which does not exist in the database that gets passed in, the model is null but I handle it in my try and catch a null reference exception but the program still crashes, is there any other way to handle this sort of general error?

jacky
  • 65
  • 1
  • 8
  • 1
    You really shouldn't be catching NREs anyway. Those usually signal things that should be tracked down and fixed. – Broots Waymb Nov 29 '21 at 15:32
  • `but the program still crashes` ← Are you sure it is an NRE that is being thrown? – Igor Nov 29 '21 at 15:33
  • @BrootsWaymb Hi! Could you suggest any other alternative methods to get around returning a null object? – jacky Nov 29 '21 at 15:34
  • 2
    You'll only get a `NullReferenceException` if something actually tries accessing a function or property _on_ the object. Nothing in this shown code does that. The only effect of this is that the returned `model` will be null, which you can check easily, just like before. Personally I'd invert that null check to `if (employee == null) return null;`, and put your main handling code behind that, though; to avoid getting too many indentation levels. – Nyerguds Nov 29 '21 at 15:34
  • @Igor Hi, yes, because after the program crashes, I click continue and my catch gets hit, the code inside is being hit by my breakpoints. – jacky Nov 29 '21 at 15:35
  • 1
    @jacky So did you actually _look_ at the stack trace in that exception to see where it crashed? It should tell you the exact line where something tried to access a function or property on some object that was null. – Nyerguds Nov 29 '21 at 15:37
  • @Nyerguds Hi dude! When I run the program, the model assignment in the try and catch is crying because its null, but shouldnt the try catch it before it breaks and go to catch? – jacky Nov 29 '21 at 15:37
  • 2
    See also [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/q/4660142/1260204) – Igor Nov 29 '21 at 15:37
  • @Nyerguds yes sir, the code breaks at: model = await employeeService.GetEmployeeById(Id); this is crying about model being null – jacky Nov 29 '21 at 15:38
  • @jacky This is a threading issue. I'm fairly sure it will not catch things running on a different thread. Put your try-catch around all code inside `employeeService.GetEmployeeById` instead. – Nyerguds Nov 29 '21 at 15:39
  • 1
    Wait, are you sure `employeeService` is not null, then? All that info should be in the exception's data. Just put a breakpoint there and hover your mouse over `ex`. – Nyerguds Nov 29 '21 at 15:40
  • My repo call returns null if the Id does not exist in the database, in the event that the Id does exist in the database, it will return that employee. When the Id does not exist, it will make the model null, which is where it does not like this. I put a try and catch around it so it could try the piece of code, and catch the error when it is null.... BUT! It still crashes and cries that the model is null, then when I hit continue on the code, it then goes into the catch and executes the code inside the catch. – jacky Nov 29 '21 at 15:47
  • 1
    I also think your object, `employeeService` is not initialized. It never makes it to the get function because it doesn't exist on a null object – Jawad Nov 29 '21 at 16:09
  • @jacky `When the Id does not exist, it will make the model null` - I'm not sure you're using the word "model" correctly here, but we were talking about `employeeService` itself, not the returned object. Check if it is null _before_ that call. – Nyerguds Nov 30 '21 at 11:13
  • @Nyerguds hi dude, when I call the _repo.getEmployeeById(Id) with a invalid id, of course it will return null because the employee with that id does not exist in ssms. In addition to that, when this call returns null, it will return null altogether anyways because i've specified that under the if statement. – jacky Nov 30 '21 at 11:24
  • Do you ever even get _into_ that getEmployeeById function though? Does it work with a _valid_ id? Put breakpoints. Debug. – Nyerguds Nov 30 '21 at 12:53
  • yes, this gets hit everytime a user clicks on a button. The button will fire up this try statement: model = await employeeService.GetEmployeeById(Id); In turn, this call will go to another method which calls this: var employee = _repo.GetEmployeeById(Id);. – jacky Nov 30 '21 at 13:34
  • The problem im having is that when the user types into the URL for example: https://localhost:5001/employee/view/{Id} where Id is an integer, if the Id does not exist, the website says "an unhandled exception has occurred. See browser dev tools for details. Reload" and when you go to the browser dev tools it says "Error: System.NullReferenceException" because obviously, im trying to reference an object which does not exist – jacky Nov 30 '21 at 13:36
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Wai Ha Lee Dec 01 '21 at 06:28

1 Answers1

0

You should first understand what a NullReferenceException is: what is a NullReferenceException and how do I fix it

If you don't know the generated exception and want your program to catch the error you should use a default exception first : catch(Exception ex)

When you know which exception is generated then you can add a specialized catch block your code should look like this :

try{
  //Your code
}
catch(YourException yEx){//Do something}
catch(Exception ex){//Do something}
Gerhard
  • 6,850
  • 8
  • 51
  • 81