Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null test versus try catch

Tags:

c#

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?

like image 869
mson Avatar asked Dec 09 '09 14:12

mson


People also ask

Is it better to use if-else or 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.

What is faster try catch or if?

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.

When should we use try catch?

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.

Why we use throws instead of try catch?

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.


2 Answers

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.

like image 89
Nathan Wheeler Avatar answered Nov 15 '22 17:11

Nathan Wheeler


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.

like image 39
Francis Upton IV Avatar answered Nov 15 '22 17:11

Francis Upton IV