Does anyone have metrics on performing null test versus wrapping code in a try catch?
I suspect that the null test is much more efficient, but I don't have any empirical data.
The environment is C#/.net 3.x and the code comparison is:
Dude x = (Dude)Session["xxxx"];
x = x== null ? new Dude(): x;
versus
Dude x = null;
try {
x = (Dude)Session["xxxx"];
x.something();
} catch {
x = new Dude();
}
are there any advantages to wrapping in try catch?
In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen. Edit: Also, catch blocks won't stop your code from halting when an error is hit.
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.
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. 5. finally: It is executed after the catch block.
Exceptions do take extra memory, as well as time, to catch. It is ALWAYS better to test for null if it's a possible value.
Another thing to consider it that it's simply less code and more readable to do the null test. Usually having try/catch blocks adds essentially no overhead to your code for the normal case, but when the exception is triggered it's quite expensive.
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