When To Use Try-Catch In C#
Today, I want to talk about using try catch blocks in our Asp.net projects. Most of all think that, using try-catch blocks in our code is a must. We use try catch mechanism in order to catch errors in our codes. And this is very useful for us to control unexpected errors in our code.
1 2 3 4 5 6 7 8 9 10 |
int x=1; int y=0; try { Console.WriteLine("x/y={0}",x/y); } catch { Console.WriteLine("undefined"); } |
But one thing we abduct in this mechanism. That is using try catch blocks make your programs much slower. Because the compiler compiles all the code and then decides to throw an exception if an error happens. This is very costly process for your application. So if performance is an issue for you, do not use try-catch blocks as you can. Instead, control your code with if else blocks like this :
1 2 3 4 5 6 |
int x=1; int y=0; if(y==0) Console.WriteLine("undefined"); else Console.WriteLine("x/y={0}",x/y); |
Remember, you can use this method which possible code errors are predictable and you can control them. If your code is more complex (file, database operations vs..) and you could not find all of the possible errors then use try-catch blocks. Do not forget to throw errors. You do not want to write a code that swallows errors. You should have a look at my another post about Session Authorization In Asp.Net
If you have question do not forget to write from the chat button next to it or from the comment.
Recent Comments