Handling Errors in Razor Syntax

In this chapter you will learn
  • How to handle errors in Razor Syntax?
  • Try Catch Finally
  • Programming Example

How to handle errors in Razor Syntax?

As you know razor allows you to full implementation of c# or vb so you can use exception handling inside razor syntax with try, catch, finally block.

Programming Example

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @functions{
            public int divide(int x, int y)
            {
                string errormessage;
                try
                {
                return x/y;
                }
                catch(DivideByZeroException d)
                {
                    errormessage = d.ToString();
                    WriteLiteral("<br />Cannot Divide by Zero Exception found <br /><br />");
                    WriteLiteral("Additional Info <br /><br />" + errormessage);
                    return 0;
                }
            }
        }
        <h3>Division of 10 / 5 is @divide(10,5)</h3>
        <h3>Add of 12 + 0 is @divide(12,0)</h3>
    </body>
</html>
  Output
Division of 10 / 5 is 2
Add of 12 + 0 is
Cannot Divide by Zero Exception foundAdditional Info

System.DivideByZeroException: Attempted to divide by zero. at ASP._Page_index_cshtml.divide(Int32 x, Int32 y) in c:\Users\Prashant\Documents\My Web Sites\EmptySite5\index.cshtml:line 190

Summary

In this chapter you learned how to use try catch exception handling in razor syntax. In the next chapter you will get some practice question to solve. You must solve them using programming logic. It will help you to gain better understanding of Razor Syntax.
 

Share your thought