Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Try/Catch/Finally [closed]

I have been taught for the most part to always remove try/catch/finally blocks from my code. The reason behind this always made sense to me (if your application works the way it should, you don't need to prevent errors), but at the same time there are so many things that can cause errors that aren't due to poor coding; server hiccups, graphics seem to never fail when it comes to failing out for no apparent reason, etc. I have also been told these blocks can decrease performance, nothing I've noticed personally when I used them, but I guess this could be the case. Basically what I'm getting to is; Try/Catch/Finally a bad overall idea or another one of those good in certain cases, bad when overused for poor code to keep the application afloat, good for testing/bad for production? Just wanted some input.

like image 630
Volearix Avatar asked Dec 19 '22 20:12

Volearix


2 Answers

There are situations where you can't really avoid Try/Catch,

Consider a situation where you want the user to input some data to be entered in a database table. User's input includes primary key as well, Now if some user enters a duplicate primary key, you will get an exception. What do you want to do now ? let the system crash or handle the exception and show a user friendly message to user for inputting something different/unique.

Consider an example, Suppose you want to check if some URL is valid and available you might need some method like: (take from here)

private bool IfURLExists(string url)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "HEAD";
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch //may catch specific WebException First
    {
        return false;
    }
}

The above method would not work without try/catch.

Another important usage of try/finally is with using statement, using works with those object which implements IDisposable interface and translates into try/finally block so if an exception occurs it would ensure the disposal of unmanaged resource.

Generally catch only those exceptions if you want to do something useful with them, otherwise let the exception bubble up

like image 119
Habib Avatar answered Dec 22 '22 10:12

Habib


There is absolutely nothing wrong in using try/catch/finally blocks, if they are used in a thoughtful manner.

As a developer you cannot even imagine how different from you a customer can think, or how your system is going to interact with different systems or react to inputs you didn't thought of.

The only rule is: Do not abuse.

like image 38
DocKuro Avatar answered Dec 22 '22 11:12

DocKuro