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 various problems. Sometimes the trouble is acquired by bad code; other times, a problem is caused by bad user input that has not been deemed for in the application's code. Regardless of the crusade of the problem, the end result is that the application does non work every bit expected. At this betoken, we say the application has encountered an error. In .Internet, exceptions are thrown when a running awarding encounters an error.

What Are Exceptions?

An exception is a runtime error in a program that violates a system or awarding constraint, or a condition 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 zero or opening a corrupted XML file. When these occur, the organization catches the error and raises an exception.

Throwing Exceptions

When a state of affairs occurs that violates a system or awarding constraint, it can generate an exception to signal to the caller that an operation has failed. The process of generating and signaling the error is referred to equally throwing exception. This is washed using the throw keyword followed by a new case of a class deriving from Arrangement.Exception . Permit's look at an example. Create a new panel projection and update Program.cs with the code below.

                                      1                    using                                                            System                    ;                                                            2                    3                                        namespace                                                            MyApp                                                            iv                                        {                                                            5                                                            class                                                            Programme                                                            vi                                                            {                                                            7                                                            static                                                            void                                                            Main                    (                    string                    [                    ]                                          args                    )                                                            8                                                            {                                                            9                                                            var                                          radio                                        =                                                            new                                                            Radio                    (                    )                    ;                                                            10                                          radio                    .                    SetVolume                    (                    120                    )                    ;                                                            eleven                                                            }                                                            12                    xiii                                                            class                                                            Radio                                                            14                                                            {                                                            15                                                            public                                                            int                                          Volume                                        {                                                            go                    ;                                                            ready                    ;                                                            }                                                            sixteen                                                            public                                                            string                                          Station                                        {                                                            go                    ;                                                            set                    ;                                                            }                                                            17                    18                                                            public                                                            void                                                            SetVolume                    (                    int                                          volume                    )                                                            19                                                            {                                                            20                                                            if                                                            (                    volume                                        >                                                            100                    )                                                            21                                                            {                                                            22                                                            throw                                                            new                                                            ArgumentOutOfRangeException                    (                    nameof                    (                    volume                    )                    ,                                                            "volume cannot exist more than than 100"                    )                    ;                                                            23                                                            }                                                            24                    25                                          Book                                        =                                          volume                    ;                                                            26                                                            }                                                            27                    28                                                            public                                                            void                                                            SetStation                    (                    string                                          station                    )                                                            29                                                            {                                                            xxx                                                            if                                                            (                    string                    .                    IsNullOrEmpty                    (                    station                    )                    )                                                            31                                                            {                                                            32                                                            throw                                                            new                                                            ArgumentNullException                    (                    nameof                    (                    station                    )                    ,                                                            "you cannot tune to an empty station"                    )                    ;                                                            33                                                            }                                                            34                    35                                          Station                                        =                                          station                    ;                                                            36                                                            }                                                            37                                                            }                                                            38                                                            }                                                            39                                        }                                  

csharp

In the code example above, nosotros divers a Radio class, the properties Station and Volume , and methods SetStation and SetVolume . When the SetVolume method is called with a value greater than 100, the application throws an ArgumentOutOfRangeException with the parameter proper name and exception message as arguments. Similarly, when SetStation method is chosen with an empty cord, it throws an ArgumentNullException with the parameter name and exception bulletin as arguments.

If nosotros run the awarding and it crashes, it will impress out the exception message and stack trace tells united states where the mistake occurred in the panel. The information that it'll give yous should be similar to what is displayed in the paradigm beneath:

throw exception.png

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

Re-throwing Exceptions

The exception from the previous section propagates up the call stack and since we have no lawmaking to catch and handle the exception, it crashes. When an exception is caught, we can perform some operations, like logging the error, and and so re-throw the exception. Re-throwing an exception means calling the throw argument without an exception object, inside a catch block. Information technology can only be used inside a catch block.

Let'southward create a new console application and update the Plan.cs file with the following:

                                      1                    using                                                            System                    ;                                                            2                    three                                        namespace                                                            MyApp                                                            4                                        {                                                            5                                                            class                                                            Program                                                            6                                                            {                                                            vii                                                            static                                                            void                                                            Main                    (                    string                    [                    ]                                          args                    )                                                            8                                                            {                                                            9                                                            var                                          calculator                                        =                                                            new                                                            Calculator                    (                    )                    ;                                                            10                    11                                          Console                    .                    WriteLine                    (                    "Enter number"                    )                    ;                                                            12                                                            int                                          number                                        =                                                            int                    .                    Parse                    (                    Console                    .                    ReadLine                    (                    )                    )                    ;                                                            13                    14                                          Console                    .                    WriteLine                    (                    "Enter divisor"                    )                    ;                                                            15                                                            int                                          divisor                                        =                                                            int                    .                    Parse                    (                    Console                    .                    ReadLine                    (                    )                    )                    ;                                                            16                    17                                          Console                    .                    WriteLine                    (                    calculator                    .                    Divide                    (                    number                    ,                                          divisor                    )                    )                    ;                                                            18                                                            }                                                            19                    20                                                            form                                                            Calculator                                                            21                                                            {                                                            22                                                            public                                                            int                                                            Divide                    (                    int                                          number                    ,                                                            int                                          divisor                    )                                                            23                                                            {                                                            24                                                            endeavor                                                            25                                                            {                                                            26                                                            render                                          number                                        /                                          divisor                    ;                                                            27                                                            }                                                            28                                                            catch                                                            (                    DivideByZeroException                    )                                                            29                                                            {                                                            30                                                            //TODO: log mistake                                                            31                                          Console                    .                    WriteLine                    (                    "Tin can't separate past 0"                    )                    ;                                                            32                                                            throw                    ;                    //propage this fault                                                            33                                                            }                                                            34                    35                                                            }                                                            36                                                            }                                                            37                                                            }                                                            38                                        }                                  

csharp

From the code above, we accept a Calculator class with Divide method. In .NET, when a number is being divided past 0, information technology throws the DivideByZeroException . In the Divide method, we have code to grab this exception, log to the console, and re-throw the exception. Run the awarding and enter a divisor of 0:

re-throw exception.gif

You can see that when we passed it 0 as a divisor, information technology printed Tin can't divide by 0 to the panel before re-throwing the exception. Notice that the stack trace still maintained proper data, pointing to line 26 as the line that the error occurred at, even though it was re-thrown on line 32. A common mistake people brand when they intend to re-throw exception is to telephone call the throw keyword with the defenseless exception object. An example of this is equally follows:

                                      i                    grab                                                            (                    DivideByZeroException                                          ex                    )                                                            2                                        {                                                            3                                                            //TODO: log error                                                            four                                          Console                    .                    WriteLine                    (                    "Can't separate past 0"                    )                    ;                                                            5                                                            throw                                          ex                    ;                    //propage this mistake                                                            6                                        }                                  

csharp

If we had it implemented this manner, it'll print out the following stack trace:

                                      1                    Unhandled Exception: System.DivideByZeroException: Attempted to divide past zero.                                        2                    at MyApp.Program.Calculator.Divide(Int32 number, Int32 divisor) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Programme.cs:line 32                    3                    at MyApp.Program.Master(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Programme.cs:line 17                                  

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

That's a Wrap

Sometimes an mistake occurs in our application because of bad code, other times, it is acquired by bad user input that has not been deemed for in the application'southward code. An exception is thrown when an error is encountered in a running awarding. In this guide nosotros looked at using the throw keyword for throwing and re-throwing exception and explained the correct syntax for re-throwing exception.

johnsonupoorde.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