• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級(jí)} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            Exception Handling in C#

             Exception Handling in C#

            In this article, you will learn about the usage of various exception handling statements in C# with the help of relevant listings.

            Trapping and handling of runtime errors is one of the most crucial tasks ahead of any programmer. But, before discussing runtime errors, let's look at compile time errors, which are errors that occur during compilation time. They may be due to bad coding, misspelling of syntaxes, and so on. They can be corrected by studying the error messages and warnings the compiler produces.

            On the other hand, runtime errors occur at the time the program executes and can't be corrected. A programmer can, however, take preventive measures while coding the program. To do so, a programmer should first identify these two aspects:

            • Find out the part or parts of a program that are most likely to emit runtime errors.
            • Handle those errors according to language conventions.

            C# provides an elegant way to handle runtime errors with the help of the try, catch, and finally keywords. Before moving ahead, let's consider a situation where the exception is not handled. We will explain the concept with the help of a "Division by Zero" example. Listing 1 illustrates how to write a simple program without handling an exception:

            Listing 1

            class  Without
            {
              public static void Main()
              {
                int x = 5;
                int y = 0;
                int z = x/y;
                Console.WriteLine(z);
              }
            }
            

            When you execute this program, the C# interpreter produces a series of error messages (see Figure 1) to notify you that a runtime error has occurred.



            Click here for a larger image.

            Figure 1—Exception Occurred

            To avoid these error messages and provide the user with a user-friendly error message, you should enclose the error-prone areas in Listing 1 with the try-catch clause, as shown in Listing 2:

            Listing 2

            class  With
            {
              public static void Main()
              {
                try
                {
                  int x = 5;
                  int y = 0;
                  int z = x/y;
                  Console.WriteLine(z);
                }
                catch(DivideByZeroException e)
                {
                  Console.WriteLine("Error occurred, unable to compute");
                }
              }
            }
            

            When you execute the program in Listing 2, instead of error messages as in Figure 1, the statement inside the catch block (see Figure 2) would be printed as our output.



            Click here for a larger image.

            Figure 2—Exception Handled Successfully

            DivideByZeroException is one of the built-in exceptions in C#, defined in the System namespace. There are lots of other exceptions, which we will discuss shortly. The base class of all Exception classes in the .NET Framework is System.Exception. Even though the System namespace defines lot of exceptions, some of them are specified in specialized namespaces such as System.Data, System.IO, and so forth. Table 1 describes some of the built-in exceptions defined in the System namespace.

            Name Description of Probable Causes
            ArithmeticException Data Type not matched, invalid casting, etc.
            DivideByZeroException An attempt to divide a value by zero
            FormatException Incorrect arguments for the methods
            MissingMethodException An attempt to call an invalid method
            OutOfMemoryException Not enough memory to complete an operation
            OverflowException An attempt to give large values to a variable of some type

            Table 1—Built-in Exceptions

            In Listing 2, we have analyzed DivideByZeroException and the way to handle the same. There are many more examples, which you may try on your own.

            Using the finally Clause

            In the preceding listings, the statements inside the catch block would be executed only if an error occurs. If you substitute the value of y with 1 and execute, there will not be an exception. However, there may be some cases where you want something to be printed, whether the exception had occurred or not. You can do so by using the finally clause. Listing 3 illustrates this concept by revisiting Listing 2:

            Listing 3

            class  Withfinally
            {
              public static void Main()
              {
                try
                {
                  int x = 5;
                  int y = 0;
                  int z = x/y;
                  Console.WriteLine(z);
                }
                catch(DivideByZeroException e)
                {
                  Console.WriteLine("Error occurred, unable to compute");
                }
                finally
                {
                  Console.WriteLine("Thank you for using the program");
                }
              }
            }
            

            In the Listing 3 code, the statement inside the finally block will always print as shown in Figure 3.



            Click here for a larger image.

            Figure 3—Using the finally Clause

            Using the Message Property

            In certain cases, you may have to print the built-in C# error messages when a runtime error occurs. The System.Exception namespace defines predefined error messages for every exception. To use them, you have to use the Message property found in the System.Exception namespace. Listing 4 illustrates the working of this property.

            Listing 4

            class WithMessage
            {
              public static void Main()
              {
                try
                {
                  int x = 5;
                  int y = 0;
                  int z = x/y;
                  Console.WriteLine(z);
                }
                catch(DivideByZeroException e)
                {
                  Console.WriteLine("Error occurred " +e.Message);
                }
              }
            }
            -------------------------------------------------------------------

            About the Author

            Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials.

            posted on 2005-11-18 12:03 夢(mèng)在天涯 閱讀(729) 評(píng)論(0)  編輯 收藏 引用 所屬分類(lèi): C#/.NET

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評(píng)論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類(lèi)

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1807508
            • 排名 - 5

            最新評(píng)論

            閱讀排行榜

            99久久精品毛片免费播放| 久久精品国产色蜜蜜麻豆| 国产一区二区久久久| 97久久国产露脸精品国产| 亚洲精品乱码久久久久久久久久久久| 亚洲综合伊人久久综合| 亚洲成色www久久网站夜月| 日韩欧美亚洲综合久久| 久久精品国产亚洲αv忘忧草| 久久天天婷婷五月俺也去| 久久综合中文字幕| 亚洲日韩欧美一区久久久久我| 精品国产乱码久久久久久1区2区| 亚洲国产成人久久精品影视 | 久久综合狠狠综合久久综合88| 久久国产乱子精品免费女| 久久久久久国产精品无码下载| 久久国产乱子伦精品免费午夜| 欧美久久综合性欧美| 日韩精品国产自在久久现线拍 | 久久久国产精品亚洲一区| 国产A级毛片久久久精品毛片| 国产午夜免费高清久久影院| 日韩精品久久久肉伦网站 | 久久精品一区二区三区AV| 久久99国产精品久久久| 久久久久国产一区二区| 97精品依人久久久大香线蕉97| 色成年激情久久综合| 99久久无色码中文字幕| 精品人妻伦九区久久AAA片69| 久久精品国产精品亚洲精品| 97精品伊人久久久大香线蕉| 国产三级久久久精品麻豆三级| 7777精品伊人久久久大香线蕉 | 亚洲国产精品一区二区三区久久 | 久久精品无码一区二区三区| 亚洲人成伊人成综合网久久久 | 久久久久亚洲精品中文字幕| 精品久久久久久国产| 99久久人妻无码精品系列蜜桃|