Error handling one of the most important part of an
application development. In this article
I will show you how you can use try , catch and finally block in your mvc application.
Some of previous articles are as follows: Increase
Session TimeOut in MVC 4, Simple
Login From in Asp.Net MVC Using C#.Net, Bind
and Retrieve ListBox Selected Value in MVC Using C#.Net, Bind
DropDownList Using Entity Framework in ASP.Net MVC Using C#, Error
: SQL Server Compact is not intended for ASP.NET development. .
So for this article first we will create a new mvcapplication and add a model in our application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ErrorHandeling_In_MVC.Models
{
public class ErrorModel
{
public
string ErrorMessage { get; set; }
public
string FinallyBlockMesage { get; set; }
}
}
|
Now we will create our controller and add the below code in
our controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ErrorHandeling_In_MVC.Models;
namespace ErrorHandeling_In_MVC.Controllers
{
public class HomeController
: Controller
{
//
// GET:
/Home/
/// <summary>
/// Track and Display error message in mvc application using
c#.Net
/// </summary>
/// <returns></returns>
public
ActionResult Index()
{
ErrorModel
objerrormodel = new ErrorModel();
try
{
int
value1 = 0;
int
value2 = 2;
int
finalvalue = value2 / value1;
}
catch
(Exception ex)
{
objerrormodel.ErrorMessage =
ex.Message.ToString();
}
finally
{
objerrormodel.FinallyBlockMesage = "This
message assign in finally block.";
}
return
View(objerrormodel);
}
}
}
|
In above code we have raised exception by dividing by zero
to a number. We will catch exception in
catch block and finally we will raise the final block effect.
Now we will create view in for our controller. Now we will
check the view code.
@model ErrorHandeling_In_MVC.Models.ErrorModel
@{
ViewBag.Title = "Index";
}
<h2>Error
Handeling</h2>
<ul>
<li>Error
Message :@Model.ErrorMessage</li>
<li>Finally
Block :@Model.FinallyBlockMesage</li>
</ul>
|
Now run the application. You will get the exception as shown
below.
And final output
0 comments:
Please let me know your view