Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use specific exception catch blocks

In the code below, I have a catch block for System.Data.Entity.Infrastructure.DbUpdateException class exception.

My question is that why I can't use Exception class to catch each and every possible exception in my code and get stacktrace?

What is the advantage of specific exception types and their use in multiple catch blocks?

try
{
    AddAdminUserInput input1 = JsonConvert.DeserializeObject<AddAdminUserInput>(input);
    Foundation_Services_DL_DataEntities Db = DLMetadataContext.GetContext();
    UserAccount account = new UserAccount
    {
        emplid = input1.emplid,
        sso = input1.sso,
        deptid = input1.deptid,
        usertype = input1.usertype,
        status = input1.status,
        username = input1.username
    };

    Db.UserAccounts.Add(account);
    Db.SaveChanges();

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("status", "0");
    dict.Add("message", "User Addition Successful");

    Context.Response.Write(JsonConvert.SerializeObject(dict));
}
catch (System.Data.Entity.Infrastructure.DbUpdateException dbev)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("status", "1");
    dict.Add("message", "User Addition Failed - User Already Exists");

    Context.Response.Write(JsonConvert.SerializeObject(dict));
}
like image 434
BILAL AHMAD Avatar asked Nov 28 '17 20:11

BILAL AHMAD


People also ask

Should you catch specific exceptions?

A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can. Catching all exceptions at language borders to translate them is also good practice.

Why are try catch blocks useful?

One of the benefits of try/catch is its ability to display your own custom-created error. This is called (throw error) . In situations where you don't want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement.

Why the order of catching exceptions is important when multiple catch blocks are used in a program?

Since Exception is the superclass of all the exception classes, if you place the catch block that catches it earlier to the catch blocks catching any other exceptions, all exceptions are handled in the Exception block itself making the remaining blocks unreachable.

What is the function of catch block in exception handling?

A catch -block contains statements that specify what to do if an exception is thrown in the try -block. If any statement within the try -block (or in a function called from within the try -block) throws an exception, control is immediately shifted to the catch -block.


1 Answers

What is the advantage of specific Exception types and their use in multiple catch blocks?

A better way to ask the same question is "what is a disadvantage of catching less specific Exception types." The answer to this question is very straightforward: you could inadvertently catch an exception that you do not know how to handle.

As a rule, the code should catch an Exception only when it knows what to do with it, e.g. report an error, retry with a counter, ask end-user for a decision on how to proceed, and so on. This is possible only when you limit the exceptions that you catch to a specific group, such as DbUpdateException.

A nice "bonus" for catching specific exceptions is that you get access to properties and methods defined only on the specific subclasses. For example, DbUpdateException tells you which entries failed to save through Entries property, which gives you an opportunity to attempt a retry.

Finally, certain exceptions are meant to be caught only at the top-level of your program. These exceptions indicate programming errors - for example, accessing a null reference, accessing an array past the end or at a negative index, dividing by zero, and so on. There is nothing your program could do to recover from these errors, because fixing them requires a code change. Therefore, the only thing the program could do is to log or otherwise report the exception before exiting or initiating a restart sequence.

like image 152
Sergey Kalinichenko Avatar answered Oct 19 '22 20:10

Sergey Kalinichenko