C # Try / Catch / Finally

I was mostly taught to always remove try / catch / finally blocks from my code. The reason for this always made sense to me (if your application works as it should, you do not need to prevent errors), but at the same time there are so many things that can cause errors that are not related to bad coding; server hiccups, the graphics never seem to fail when it comes to failure for no apparent reason, etc. I was also told that these blocks can reduce performance, I didn’t notice anything personal when I used them, but I think this may be the case. Basically what I relate to; Try / Catch / Finally, a bad general idea or one of those that are good in some cases, bad when abused for bad code, to keep the application afloat,good for testing / bad for production? Just wanted to do my part.

+4
source share
5 answers

There are situations where you really cannot escape Try/Catch,

Consider a situation where you want the user to enter some data to enter into a database table. User input also includes a primary key. Now, if any user enters a duplicate primary key, you will get an exception. What would you like to do now? let the system fail or handle the exception and show the user a message convenient for the user to enter something else / unique.

. , , - URL, - : ( )

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;
    }
}

Try/Catch.

try/finally using, using , IDisposable try/finally, , , .

, , - ,

+5

try/catch/finally, .

, , , .

: .

+2

, try/catch/finally.

, , , ? , ?

# language using, , try/finally. ? ? try/finally?

foreach try/finally , .

: " ". SocketException IOException ? ? . , .

: try/catch/finally , . , , . .

+2

- , . , . , , .

+1

You should only catch exceptions that you can deal with, others should bubble up. You should definitely not catch exceptions such as NullReferenceExceptionor ArgumentOutOfRangeException. These are errors and traps that hide these errors in your code.

Related article: Vexing Exceptions

+1
source

All Articles