How to throw good exceptions?

前端 未结 12 1356
情话喂你
情话喂你 2020-12-14 21:05

I heard you should never throw a string because there is a lack of information and you\'ll catch exceptions you dont expect to catch. What are good practice for throwing exc

12条回答
  •  -上瘾入骨i
    2020-12-14 22:02

    As it has been already said use them for exceptional situations only.

    Always provide a way for the user to avoid throwing an exception, eg. if you have method, that will throw if something goes wrong like this:

    public void DoSomethingWithFile() {
        if(!File.Exists(..))
            throw new FileNotFoundException();
    }
    

    Provide another method for the user to call:

    public bool CanDoSomething() {
        return File.Exists(..);
    }
    

    This way there the caller can avoid exceptions if he wants. Do not hesitate to throw if something is wrong - "fail fast", but always provide exception-free path.

    Also keep your exception class hierarchy flat and take a look at the standard exceptions like InvalidStateException and ArgumentNullExcpetion.

提交回复
热议问题