开发者

When to use assert() and when to use try catch?

I开发者_StackOverflow社区n which situations do you use them?


Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.

Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.

Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.


When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.


Normally assert() does not work in release code, so it can never replace a try-catch strategy. Nevertheless I like to use assert() in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by an assert() message to the line of failure than through the exception stack.


They are created for different purposes. Assert is more for finding bugs, try-catch is for handling exceptional situations.


The situations of try-catch and assert are totally different. Assert is used to check if the value you have received, as parameter for example, is expected. I would not recommend to use assert in production code, it is used in unit-test mostly and rarely to check the parameters. To check the passed values better to use something like:

public void test(int i) {
  if (i < 0) {
    throw new IllegalArgumentException("i cannot be less than 0");
  }
  ...
}

Try-catch block is used when you know something inside the block can go wrong. For example, you write to an sdcard and there is no space for writing. Or, it happened that you try to read the array out of it bounds. Then, you put your critical code in try-catch block and check for the excpetions:

try {
  InputStream is = new FileInputStream("filename.txt");
  ...
} catch FileNotFoundExcpetion {
  System.out.println("file not found");
} finally {
 ...
}

More about exceptions and try-catch blocks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜