Showing posts with label exception. Show all posts
Showing posts with label exception. Show all posts

Friday, December 5, 2014

Exception handling in asp.net mvc using HandleError Attribute

hi in this post i will show how to use handleError attribute for exception handling in asp.net mvc.

we can add handleError attribute around the whole controller class or just around the individual action methods.
1
next we need to add
<customErrors mode=”On”></customErrors> 
in the webconfig file.
10-25-2014 8-51-02 PM

Now in the view folder we will create a shared folder and in that we will add a view page called error.cshtml
so whenever there is any exception it will get redirected to this page.
we will create a strongly typed view which will have model HandleErrorInfo
error.cshtml code:
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>error</title>
</head>
<body>
<div>
Error Occured !!!
<table border=”1″>
<tr>
<td>
Controller Name: @Model.ControllerName
</td>
<td>
Action Name: @Model.ActionName
</td>
<td>
Exception Details: @Model.Exception
</td>
</tr>
</table>
</div>
</body>
</html>
model HandleErrorInfo code :
public class HandleErrorInfo
{
public string ActionName { get; set; }
public string ControllerName { get; set; }
public Exception Exception { get; set; }
}

Output:
Now run the application
error

Friday, January 10, 2014

examples for using try-catch-finally block in asp.net

In this post i will show how to use try-catch-finally block in asp.net.
try block has to be used accompanied my catch block or finally block or both.

1. Using  try-catch-finally block ( Finally block will be executed whether there is a exception or not )

Example :
             try
            {
                int a = 10;
                int b = 0;
                int z = a / b;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
              
            }
            finally
            {
                Console.WriteLine("Finally Block");
                Console.ReadLine();
            }



2. Using try-finally block (No Exception handled here as the catch block is removed)

Example :

          try
            {
                int a = 10;
                int b = 10;
                int z = a / b;
            }
           
            finally
            {
                Console.WriteLine("Finally Block");
                Console.ReadLine();
            }



3.  Using try-catch block

Example :

             try
            {
                int a = 10;
                int b = 0;
                int z = a / b;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }