Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




ASP.NET MVC interview questions: - Explain Exception Handling in MVC?

Now a days during ASP.NET MVC interview questions interviewer revolve around exception handling question. So in this article we will try to answer it.

In MVC we have many choices by which we can handle exceptions. Following are the ways to achieve exception handling in MVC: -

  • Using try....Catch

public ActionResult MyAction()

{

try

    {

//....

return View();

    }

catch ( Exception e)

    {

//Handle Exception;

return View( "Error" );

    }

}

  • Using Overriding OnException method of controller class

protectedoverridevoid OnException( ExceptionContext filterContext)

{

Exception e = filterContext.Exception;

 

    filterContext.Result = new ViewResult ()

    {

        ViewName = "Error"

    };

}


When we use HandleError Attribute we will be get Error view in return automatically whenever exception occurs.

1. In Controller level.

[ HandleError ()]

publicclass TestingController : Controller

{

public ActionResult MyAction()

    {

//.....

return View();

    }

}

//It will handle all exceptions raised by every action method in the controller class.   

2. In Action Level

[ HandleError ()]

public ActionResult MyAction ()

{

//.....

return View();

}

3. In Global Level

GlobalFilters .Filters.Add( new HandleErrorAttribute ());

//It will handle all exceptions raised by every action method in the controller class.

  • Using Application_Error attribute in Global.asax

protectedvoid Application_Error()

{

Exception e = Server.GetLastError();

//Log e

    Server.ClearError();

}


Note: We have uploaded a supporting article for our step by step series. It explains in detail exception handling in ASP.NET MVC. If you are willing to read more about it, click here.

We hope all of you enjoyed reading this article. In case you are interested in any technical training related to MVC, WCF, Design Patterns, WPF, Angular.js, TFS, UML or BI visit www.sukesh-Marla.com or contact SukeshMarla@Gmail.com

Also see following video on ASP.NET MVC interview questions video in which we will create a simple customer model/class: -

Helpful Website Url
http://questpond.com/
Share this article   |    Print    |    Article read by 4944 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles:
Related Interview Questions: No related interview question