How to decide between using if/else vs try/catch?

前端 未结 15 1373
挽巷
挽巷 2020-12-05 06:44

When writing code, how does one decide between using if/else or try/catch? For example, in checking for a file, should this be based on if/else (if (File.Exists)) or a try/c

相关标签:
15条回答
  • 2020-12-05 07:13

    As some answers have already pointed out, it depends.

    If/else are used for flow control, but so can Exceptions with the added plus of catching a error that occurs. But as Turowicz pointed out it's considered bad practice to a lot of people, to use try/catch more than the Minimum of what you have to.

    You can always read these articles from Ned Batchelder (Talks about return codes, as a alternative to using exceptions) and Joel Spolsky (Why he doesn't like programming with exceptions) to get a idea of what other think of exceptions and then make your own mind up.

    0 讨论(0)
  • 2020-12-05 07:13

    The adage "Exceptions should be exceptional" is useful when making these kinds of decisions. The principal being that you should handle known situations with standard program flow (i.e. if statements) so that exceptions represent unexpected situations (i.e. bugs).

    Of course, like any rule, it's there to be broken.

    Also, I wouldn't get too worried about the performance impact of exception handling. The overhead is pretty much negligible in all but extreme situations.

    0 讨论(0)
  • 2020-12-05 07:18

    Just a thought... one of the answers was that you should do a try catch if, for example, you have division by zero possibility. I wonder why? You are in control here, you can check before you divide, and act upon. If it's zero, you just don't need to do the division, but instead execute another logic.

    I would only use try catch in the case that you are not in control or cannot (or doesn't make sense) check things beforehand (opening a file,...).

    In your case, I would use File.Exists and try/catch. File.Exists as a business check (no need to open it when it doesn't exist), try/catch to catch any exceptions that may occur while opening the file.

    0 讨论(0)
  • 2020-12-05 07:22

    When you can already handle a situation before executing it, you should use if-else. But in situations where you can't know if something is going to work or not until you actually do it, use try-catch.

    Case 1: Valid use of Try-Catch

    boolean isNumber(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (NumberFormatException) {
            return false;
        }
    }
    

    You can't know if input is a number until you actually "try" to parse it. Hence, use try-catch.

    Case 2: Valid use of if-else

    boolean isNotNull(Object o) {
        if (o != null) {
            return true;
        } else {
            return false;
        }
    }
    

    I can know an object is null before calling a method on it. Hence, use if-else.

    Case 3: Invalid use of try-catch when if-else could have sufficed

    boolean isNotNull(Object o) {
        try {
            // Some operation of object to know it's not null
            o.hashCode();
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }
    

    Tip: Use if-else as a guard for your application, like checking null values, handle edge cases, etc. For defining different application flows, use polymorphism to have better state management.

    0 讨论(0)
  • 2020-12-05 07:24

    As it is obvious from all the answers, there is no standard/approved way to decide whether you should use one or the other. If done correctly, both methods will be effective. If done incorrectly, both methods will be inefficient.

    I prefer if/else statements when it is meaningful(i.e. inside my own functions) and Try blocks when I call functions I have no control over.

    In the above example, File.Exists() would be sufficient if you control the file(meaning no other program is likely to manipulate it) but not sufficient if there is a possibility that the file will be gone between checking and using.

    File operations, in general, are better handled with exceptions in most cases, in my experience, because these very file operations, in c#, are raising exceptions. They do not return error codes that could be checked with if statements.

    0 讨论(0)
  • 2020-12-05 07:26

    You should always use try/catch when you work with files, because the state of a file can change outside of your program.

    Consider the following code bit:

    if(File.Exists("file.txt"))
        File.Delete("file.txt")
    

    The file might have been deleted by another process right after the if statement, before the Delete() call. When you try to delete it, an exception is raised.

    When working with files there are also a lot more things to consider, that you might not be able to catch with ifs, for example the file is on a network connection that got unavailable, access rights that change, hard disk failure etc.

    These things are outside the control of your program, so you should have exception handlers in place.

    0 讨论(0)
提交回复
热议问题