Introduction:

In this article, we will explain using try-catch handling an exception in ASP.NET MVC with example.

Description:
Try-Catch :-
This is the default way of handling exceptions where we write our source code into the try block and catch the exceptions in the catch block. However, you can have multiple catch blocks for a try block. Even you can have Try-Catch blocks inside a Try block.

Try: 

 A Try block is used to encapsulate a code. If any code throws an exception within that Try block, the exception will be handled by the corresponding Catch.

Catch: 
When an exception occurs, the Catch block of code gets it. This is the place where we are able to handle the exceptions.
In this block, you can save log the error either in a file or in a database.

Below is the example for the same.

    public ActionResult Index()
        {
            try
            {
                int i = 100;
                i = i / 0;
                return View();
            }
            catch (Exception Ex)
            {
              Log.Write(Ex.Message.ToString());
                return View("Error");
            }          }

In the above example, we are handling an exception by using Try-Catch. In Try block, we have written the code that needs to be executed, however, if an error occurs, the catch bock handles the error create an error log and redirects it to View

I hope you will use it after reading.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like