Why not use exceptions as regular flow of control?

后端 未结 24 1847
心在旅途
心在旅途 2020-11-21 07:30

To avoid all standard-answers I could have Googled on, I will provide an example you all can attack at will.

C# and Java (and too many others) have with plenty of ty

24条回答
  •  醉酒成梦
    2020-11-21 08:21

    My rule of thumb is:

    • If you can do anything to recover from an error, catch exceptions
    • If the error is a very common one (eg. user tried to log in with the wrong password), use returnvalues
    • If you can't do anything to recover from an error, leave it uncaught (Or catch it in your main-catcher to do some semi-graceful shutdown of the application)

    The problem I see with exceptions is from a purely syntax point of view (I'm pretty sure the perfomance overhead is minimal). I don't like try-blocks all over the place.

    Take this example:

    try
    {
       DoSomeMethod();  //Can throw Exception1
       DoSomeOtherMethod();  //Can throw Exception1 and Exception2
    }
    catch(Exception1)
    {
       //Okay something messed up, but is it SomeMethod or SomeOtherMethod?
    }
    

    .. Another example could be when you need to assign something to a handle using a factory, and that factory could throw an exception:

    Class1 myInstance;
    try
    {
       myInstance = Class1Factory.Build();
    }
    catch(SomeException)
    {
       // Couldn't instantiate class, do something else..
    }
    myInstance.BestMethodEver();   // Will throw a compile-time error, saying that myInstance is uninitalized, which it potentially is.. :(
    

    Soo, personally, I think you should keep exceptions for rare error-conditions (out of memory etc.) and use returnvalues (valueclasses, structs or enums) to do your error checking instead.

    Hope I understood your question correct :)

提交回复
热议问题