27

In which situations do you use them?

4 Answers 4

24

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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.

1 Comment

This is a key difference, assert code is attributed with the conditional attribute so it can be skipped in release builds.
2

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.