Catch Exception and Throw Again C

Author avatar

Throw and Re-throw Exceptions in C#

Peter Mbanugo

Introduction

Writing software is a circuitous undertaking, and it is quite common for even the best software to ship with diverse problems. Sometimes the problem is caused by bad code; other times, a problem is caused by bad user input that has not been deemed for in the awarding'south code. Regardless of the cause of the problem, the end result is that the application does not work as expected. At this indicate, we say the application has encountered an error. In .NET, exceptions are thrown when a running application encounters an error.

What Are Exceptions?

An exception is a runtime mistake in a program that violates a arrangement or application constraint, or a status that is not expected to occur during normal execution of the program. Possible exceptions include attempting to connect to a database that no longer exists when a program tries to divide a number by zilch or opening a corrupted XML file. When these occur, the organization catches the error and raises an exception.

Throwing Exceptions

When a situation occurs that violates a system or application constraint, it can generate an exception to signal to the caller that an functioning has failed. The process of generating and signaling the error is referred to as throwing exception. This is done using the throw keyword followed past a new example of a course deriving from System.Exception . Permit's look at an example. Create a new console project and update Programme.cs with the code below.

                                      i                    using                                                            System                    ;                                                            2                    three                                        namespace                                                            MyApp                                                            4                                        {                                                            five                                                            class                                                            Program                                                            six                                                            {                                                            vii                                                            static                                                            void                                                            Main                    (                    cord                    [                    ]                                          args                    )                                                            8                                                            {                                                            9                                                            var                                          radio                                        =                                                            new                                                            Radio                    (                    )                    ;                                                            ten                                          radio                    .                    SetVolume                    (                    120                    )                    ;                                                            11                                                            }                                                            12                    13                                                            grade                                                            Radio                                                            fourteen                                                            {                                                            xv                                                            public                                                            int                                          Volume                                        {                                                            get                    ;                                                            set                    ;                                                            }                                                            16                                                            public                                                            cord                                          Station                                        {                                                            get                    ;                                                            fix                    ;                                                            }                                                            17                    18                                                            public                                                            void                                                            SetVolume                    (                    int                                          volume                    )                                                            nineteen                                                            {                                                            20                                                            if                                                            (                    volume                                        >                                                            100                    )                                                            21                                                            {                                                            22                                                            throw                                                            new                                                            ArgumentOutOfRangeException                    (                    nameof                    (                    volume                    )                    ,                                                            "volume cannot be more than than 100"                    )                    ;                                                            23                                                            }                                                            24                    25                                          Volume                                        =                                          book                    ;                                                            26                                                            }                                                            27                    28                                                            public                                                            void                                                            SetStation                    (                    string                                          station                    )                                                            29                                                            {                                                            30                                                            if                                                            (                    string                    .                    IsNullOrEmpty                    (                    station                    )                    )                                                            31                                                            {                                                            32                                                            throw                                                            new                                                            ArgumentNullException                    (                    nameof                    (                    station                    )                    ,                                                            "y'all cannot tune to an empty station"                    )                    ;                                                            33                                                            }                                                            34                    35                                          Station                                        =                                          station                    ;                                                            36                                                            }                                                            37                                                            }                                                            38                                                            }                                                            39                                        }                                  

csharp

In the lawmaking example above, we defined a Radio grade, the properties Station and Book , and methods SetStation and SetVolume . When the SetVolume method is chosen with a value greater than 100, the application throws an ArgumentOutOfRangeException with the parameter name and exception message as arguments. Similarly, when SetStation method is called with an empty string, information technology throws an ArgumentNullException with the parameter proper name and exception bulletin equally arguments.

If we run the application and it crashes, it will impress out the exception message and stack trace tells united states of america where the error occurred in the console. The information that it'll give you should be similar to what is displayed in the image beneath:

throw exception.png

From the stack trace information, you tin see that it points to the line where we used the throw keyword, followed by the line that called the SetVolume method. This information is very helpful when debugging.

Re-throwing Exceptions

The exception from the previous section propagates upwards the call stack and since we have no code to catch and handle the exception, information technology crashes. When an exception is caught, we tin can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only exist used inside a take hold of block.

Permit's create a new console awarding and update the Programme.cs file with the post-obit:

                                      one                    using                                                            System                    ;                                                            2                    three                                        namespace                                                            MyApp                                                            4                                        {                                                            five                                                            class                                                            Plan                                                            half-dozen                                                            {                                                            7                                                            static                                                            void                                                            Principal                    (                    string                    [                    ]                                          args                    )                                                            8                                                            {                                                            9                                                            var                                          reckoner                                        =                                                            new                                                            Calculator                    (                    )                    ;                                                            10                    eleven                                          Console                    .                    WriteLine                    (                    "Enter number"                    )                    ;                                                            12                                                            int                                          number                                        =                                                            int                    .                    Parse                    (                    Panel                    .                    ReadLine                    (                    )                    )                    ;                                                            13                    14                                          Console                    .                    WriteLine                    (                    "Enter divisor"                    )                    ;                                                            15                                                            int                                          divisor                                        =                                                            int                    .                    Parse                    (                    Console                    .                    ReadLine                    (                    )                    )                    ;                                                            16                    17                                          Console                    .                    WriteLine                    (                    calculator                    .                    Divide                    (                    number                    ,                                          divisor                    )                    )                    ;                                                            xviii                                                            }                                                            nineteen                    20                                                            class                                                            Calculator                                                            21                                                            {                                                            22                                                            public                                                            int                                                            Divide                    (                    int                                          number                    ,                                                            int                                          divisor                    )                                                            23                                                            {                                                            24                                                            effort                                                            25                                                            {                                                            26                                                            render                                          number                                        /                                          divisor                    ;                                                            27                                                            }                                                            28                                                            catch                                                            (                    DivideByZeroException                    )                                                            29                                                            {                                                            xxx                                                            //TODO: log error                                                            31                                          Panel                    .                    WriteLine                    (                    "Tin can't carve up past 0"                    )                    ;                                                            32                                                            throw                    ;                    //propage this error                                                            33                                                            }                                                            34                    35                                                            }                                                            36                                                            }                                                            37                                                            }                                                            38                                        }                                  

csharp

From the code to a higher place, we accept a Calculator form with Split method. In .Net, when a number is being divided by 0, it throws the DivideByZeroException . In the Divide method, we have code to catch this exception, log to the console, and re-throw the exception. Run the application and enter a divisor of 0:

re-throw exception.gif

You can see that when we passed information technology 0 every bit a divisor, it printed Tin can't split past 0 to the console before re-throwing the exception. Find that the stack trace however maintained proper information, pointing to line 26 as the line that the error occurred at, fifty-fifty though it was re-thrown on line 32. A common mistake people make when they intend to re-throw exception is to call the throw keyword with the caught exception object. An example of this is equally follows:

                                      1                    catch                                                            (                    DivideByZeroException                                          ex                    )                                                            ii                                        {                                                            3                                                            //TODO: log fault                                                            4                                          Console                    .                    WriteLine                    (                    "Can't divide past 0"                    )                    ;                                                            5                                                            throw                                          ex                    ;                    //propage this error                                                            6                                        }                                  

csharp

If we had information technology implemented this way, it'll print out the post-obit stack trace:

                                      1                    Unhandled Exception: Arrangement.DivideByZeroException: Attempted to split up by nothing.                                        two                    at MyApp.Program.Computer.Divide(Int32 number, Int32 divisor) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 32                    3                    at MyApp.Program.Chief(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 17                                  

You lot tin can encounter that information technology pointed to line 32, the line where the exception was thrown, rather than where information technology occurred. Re-throwing an exception is simply calling throw without an exception object.

That's a Wrap

Sometimes an error occurs in our application because of bad code, other times, information technology is caused past bad user input that has not been accounted for in the application's code. An exception is thrown when an error is encountered in a running application. In this guide we looked at using the throw keyword for throwing and re-throwing exception and explained the correct syntax for re-throwing exception.

chapplebrombsood.blogspot.com

Source: https://www.pluralsight.com/guides/throw-re-throw-expectations

0 Response to "Catch Exception and Throw Again C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel