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.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.