I would like to know, what's better or/and faster in general programming? Avoid the exception or wait for the exception?
Avoid the exception would be:
string a = null;
list = someMethod();
if(list.Length > 0 ){
a = list[0];
}
if(a!=null) ...
Or try catch exception...
string a = null;
try{
a = someMethod()[0];
catch{}
if(a!=null) ...
The keyword catch should always be used with a try. Sometimes we have an important code in our program that needs to be executed irrespective of whether or not the exception is thrown. This code is placed in a special block starting with the “Finally” keyword.
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.
You should always list catched exceptions. They are predicted. If you want to catch unpredicted exceptions and handle them the same way, you should catch RuntimeException instead.
Performance is not the most relevant concern here. The question is, which of the two leads to more readable/maintainable/testable programs. You can worry about performance later.
In general, don't use exceptions for flow control. They are effectively a non-local goto
which makes programs more difficult to read and follow. As such, they should be reserved for exceptional situations. If you can get away with not using a try-catch
block for flow control, don't. Your programs will be more readable and maintainable.
The "right" way to handle this situation is
var list = someMethod();
if(list == null || list.Length == 0) {
// handle something bad
}
string a = list[0];
if(a != null) {
// go
}
You can avoid the check that list
is not null and not empty if there is a contract (Contract.Ensures
) that guarantees the return value from someMethod
is not null and not empty.
It is true, however, that exceptions are locally expensive. Whether or not they will impact the performance of your program (i.e., are a bottleneck) is another question altogether. But used properly, exceptions are generally not a bottleneck (who cares about performance when your application is crashing?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With