views:

20

answers:

1

To verify the validity of a parameter, C language uses a bunch of IF Else conditions to determine if it is valid. In JAVA, it has Exception facility to handle this. What's usage of these two method, what's the pros and cons of these two way? Thanks!

Regards!

+1  A: 

Personally, i like assert statement.

But in this context, i prefer Try-Catch for complex problems and if-else for simpler problems.

If-else(s) aren't readable and maintainable where there are many of them, especially for complex problem. This is why try-catch comes to rescue. Assuming given input is correct, let's process it. When in some lines the given input proved incorrect, just go to catch block and returns some default value.

It's argued that try-catch is slower. Well, it's true. But how much slower? 0.1 ms? 1 ms? I will sacrifice these miliseconds for readability and maintainability.

After all, in programming, there are preconditions for every function/procedure. We all know what precondition means. The best way (my personal opinion) is to assert that all parameters fit all preconditions. This way we can assume that given input is always correct since mates in another floor already guarantee that.

jancrot