Which is better/more efficient: check for bad values or catch Exceptions in Java

前端 未结 11 1622
旧巷少年郎
旧巷少年郎 2020-12-15 08:11

Which is more efficient in Java: to check for bad values to prevent exceptions or let the exceptions happen and catch them?

Here are two blocks of sample code to ill

11条回答
  •  失恋的感觉
    2020-12-15 08:32

    To be safe, assume exceptions are expensive. They often are, and if they aren't it will at least push you towards using exceptions wisely. (Entering a try block is usually trivially cheap, since implementors do their best to make it so, even at the cost of making exceptions more expensive. After all, if exceptions are used properly, the code will enter the try block many times more often than it will throw.)

    More importantly, exceptions are a style issue. Exceptions for exceptional conditions make code simpler because there's less error-checking code, so the actual functionality is clearer and more compact.

    However, if exceptions might be thrown in more normal circumstances, there's invisible flows of control that the reader has to keep in mind, comparable to Intercal's COME FROM...UNLESS... statement. (Intercal was one of the very early joke languages.) This is very confusing, and can easily lead to misreading and misunderstanding the code.

    My advice, which applies to every language and environment I know about:

    Don't worry about efficiency here. There are strong reasons besides efficiency for using exceptions in a way that will prove efficient.

    Use try blocks freely.

    Use exceptions for exceptional conditions. If an exception is likely, test for it and handle it in another way.

提交回复
热议问题