1

I was just wondering if it's a best practice to throw errors on validation and logic like the one below. I am catching these in my OnException method in my controller and sending it back to the client via Ajax as JSON. Is throwing exceptions like this ok?

public void Update(EditTeacherModel model)
        {
            var entity = _teachersRepository.FindBy(model.Id);

            if(entity == null)
                throw new NatGeoNotFoundException("Teacher");


        }
usr
  • 168,620
  • 35
  • 240
  • 369
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

3 Answers3

2

As long as you have a special, clean exception type for this, I don't see a reason why this would be a problem. Exceptions are a convenient way to step out of multiple nested call stack frames.

Be aware, though, that exception are very slow on the CLR.

usr
  • 168,620
  • 35
  • 240
  • 369
1

Exceptions have a cost. And best practice for handling custom/business errors is to return a proper error code.

Exception handling best practices are discussed here : http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

It has also been discussed here : .NET Throwing Custom Exceptions

Community
  • 1
  • 1
Beenish Khan
  • 1,571
  • 10
  • 18
  • This came from your link. Use exceptions for errors that should not be ignored I'll use a real world example for this. When developing an API so people could access Crivo (my product), the first thing that you should do is calling the Login method. If Login fails, or is not called, every other method call will fail. I chose to throw an exception from the Login method if it fails, instead of simply returning false, so the calling program cannot ignore it. - – Mike Flynn Apr 19 '12 at 16:04
1

Exceptions are expensive. I believe they are meant for unexpected behavior of your application.

Validation erros should never throw an exception, I think.

Andrew
  • 5,395
  • 1
  • 27
  • 47