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

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.


 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.

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()
                int i = 100;
                i = i / 0;
                return View();
            catch (Exception Ex)
                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.


Leave a comment

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

you may also like